From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- .../learn/server-side/django/admin_site/index.html | 354 ++++++++ .../server-side/django/authentication/index.html | 698 ++++++++++++++++ .../learn/server-side/django/deployment/index.html | 675 +++++++++++++++ .../django/development_environment/index.html | 429 ++++++++++ .../django/django_assessment_blog/index.html | 316 +++++++ .../learn/server-side/django/forms/index.html | 661 +++++++++++++++ .../server-side/django/generic_views/index.html | 612 ++++++++++++++ .../learn/server-side/django/home_page/index.html | 383 +++++++++ files/zh-tw/learn/server-side/django/index.html | 115 +++ .../server-side/django/introduction/index.html | 306 +++++++ .../learn/server-side/django/models/index.html | 475 +++++++++++ .../learn/server-side/django/sessions/index.html | 185 +++++ .../server-side/django/skeleton_website/index.html | 388 +++++++++ .../learn/server-side/django/testing/index.html | 907 +++++++++++++++++++++ .../tutorial_local_library_website/index.html | 92 +++ .../django/web_application_security/index.html | 180 ++++ .../express_nodejs/deployment/index.html | 521 ++++++++++++ .../development_environment/index.html | 385 +++++++++ .../displaying_data/author_detail_page/index.html | 89 ++ .../displaying_data/author_list_page/index.html | 85 ++ .../displaying_data/book_detail_page/index.html | 112 +++ .../displaying_data/book_list_page/index.html | 72 ++ .../index.html | 91 +++ .../bookinstance_list_page/index.html | 71 ++ .../date_formatting_using_moment/index.html | 60 ++ .../flow_control_using_async/index.html | 137 ++++ .../displaying_data/genre_detail_page/index.html | 123 +++ .../displaying_data/home_page/index.html | 133 +++ .../express_nodejs/displaying_data/index.html | 87 ++ .../locallibrary_base_template/index.html | 71 ++ .../displaying_data/template_primer/index.html | 149 ++++ .../forms/create_author_form/index.html | 155 ++++ .../forms/create_book_form/index.html | 214 +++++ .../forms/create_bookinstance_form/index.html | 150 ++++ .../forms/create_genre_form/index.html | 294 +++++++ .../forms/delete_author_form/index.html | 167 ++++ .../server-side/express_nodejs/forms/index.html | 274 +++++++ .../learn/server-side/express_nodejs/index.html | 73 ++ .../express_nodejs/introduction/index.html | 522 ++++++++++++ .../server-side/express_nodejs/mongoose/index.html | 792 ++++++++++++++++++ .../server-side/express_nodejs/routes/index.html | 646 +++++++++++++++ .../express_nodejs/skeleton_website/index.html | 506 ++++++++++++ .../tutorial_local_library_website/index.html | 91 +++ .../zh-tw/learn/server-side/first_steps/index.html | 41 + .../\344\273\213\347\264\271/index.html" | 225 +++++ files/zh-tw/learn/server-side/index.html | 59 ++ 46 files changed, 13171 insertions(+) create mode 100644 files/zh-tw/learn/server-side/django/admin_site/index.html create mode 100644 files/zh-tw/learn/server-side/django/authentication/index.html create mode 100644 files/zh-tw/learn/server-side/django/deployment/index.html create mode 100644 files/zh-tw/learn/server-side/django/development_environment/index.html create mode 100644 files/zh-tw/learn/server-side/django/django_assessment_blog/index.html create mode 100644 files/zh-tw/learn/server-side/django/forms/index.html create mode 100644 files/zh-tw/learn/server-side/django/generic_views/index.html create mode 100644 files/zh-tw/learn/server-side/django/home_page/index.html create mode 100644 files/zh-tw/learn/server-side/django/index.html create mode 100644 files/zh-tw/learn/server-side/django/introduction/index.html create mode 100644 files/zh-tw/learn/server-side/django/models/index.html create mode 100644 files/zh-tw/learn/server-side/django/sessions/index.html create mode 100644 files/zh-tw/learn/server-side/django/skeleton_website/index.html create mode 100644 files/zh-tw/learn/server-side/django/testing/index.html create mode 100644 files/zh-tw/learn/server-side/django/tutorial_local_library_website/index.html create mode 100644 files/zh-tw/learn/server-side/django/web_application_security/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/deployment/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/development_environment/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/displaying_data/author_detail_page/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/displaying_data/author_list_page/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/displaying_data/book_detail_page/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/displaying_data/book_list_page/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/displaying_data/bookinstance_detail_page_and_challenge/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/displaying_data/bookinstance_list_page/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/displaying_data/date_formatting_using_moment/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/displaying_data/flow_control_using_async/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/displaying_data/genre_detail_page/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/displaying_data/home_page/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/displaying_data/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/displaying_data/locallibrary_base_template/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/displaying_data/template_primer/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/forms/create_author_form/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/forms/create_book_form/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/forms/create_bookinstance_form/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/forms/create_genre_form/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/forms/delete_author_form/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/forms/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/introduction/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/mongoose/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/routes/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/skeleton_website/index.html create mode 100644 files/zh-tw/learn/server-side/express_nodejs/tutorial_local_library_website/index.html create mode 100644 files/zh-tw/learn/server-side/first_steps/index.html create mode 100644 "files/zh-tw/learn/server-side/first_steps/\344\273\213\347\264\271/index.html" create mode 100644 files/zh-tw/learn/server-side/index.html (limited to 'files/zh-tw/learn/server-side') diff --git a/files/zh-tw/learn/server-side/django/admin_site/index.html b/files/zh-tw/learn/server-side/django/admin_site/index.html new file mode 100644 index 0000000000..2fce622972 --- /dev/null +++ b/files/zh-tw/learn/server-side/django/admin_site/index.html @@ -0,0 +1,354 @@ +--- +title: 'Django Tutorial Part 4: Django admin site' +slug: Learn/Server-side/Django/Admin_site +translation_of: Learn/Server-side/Django/Admin_site +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Django/Models", "Learn/Server-side/Django/Home_page", "Learn/Server-side/Django")}}
+ +

現在,我們已經為本地圖書館網站 LocalLibrary 創建了模型,我們接下來使用 Django 管理網站,去添加 一些 “真實的“ 書本數據。首先,我們展示如何用管理網站註冊模型,然後展示如何登錄和創建一些數據。本文最後,我們介紹可以進一步改進管理網站的建議。

+ + + + + + + + + + + + +
前提:先完成: Django Tutorial Part 3: Using models.
目標: +

了解 Django 管理站的優點與侷限,並使用它來為我們的模型新增一些資料。

+
+ +

概覽

+ +

Django 管理應用程序可以使用您的模型,自動構建可用於創建,查看,更新和刪除記錄的網站區域。這可以在開發過程中,節省大量的時間,從而很容易測試您的模型,並了解您是否擁有正確的數據。根據網站的類型,管理應用程序也可用於管理生產中的數據。 Django 項目建議僅用於內部數據管理(即僅供管理員或組織內部人員使用),因為以模型為中心的方法,不一定是所有用戶最好的界面,並且暴露了大量不必要的關於模型的細節。

+ +

創建基礎項目時,自動完成所有的配置文件,包含您的網站中的管理應用程序在內(有關所需實際依賴關係的信息,如有需要請看 Django docs here)。其結果是,要將模型添加到管理應用程序,你必須做的,僅僅是註冊他們。在本文末尾,我們將簡要介紹,如何進一步配置管理區域,以更好地顯示我們的模型數據。

+ +

註冊模型後,我們將展示,如何創建一個新的 “超級用戶”,登錄到該網站,並創建一些書籍,作者,書籍實例和書籍類別。這些將有助於測試我們將在下一個教程中,開始創建的視圖和模板。

+ +

註冊模型(Registering models )

+ +

首先,我們從 catalog app 中打開 admin.py (/locallibrary/catalog/admin.py),目前它長的像下面區塊,注意它已經幫你導入 django.contrib.admin

+ +
from django.contrib import admin
+
+# Register your models here.
+ +

將下方的程式碼複製貼在 admin.py 文件下方以註冊所有模型,這段程式碼簡單來說就是先將模型導入,再呼叫 admin.site.register 函式來註冊每個模型。

+ +
from .models import Author, Genre, Book, BookInstance
+
+admin.site.register(Book)
+admin.site.register(Author)
+admin.site.register(Genre)
+admin.site.register(BookInstance)
+ +
注意:如果你在上一章節最後有接受挑戰並建立一個書本的「語言模型」 (查看模型教學文章),你必需也要導入並註冊該模型!
+ +

這是註冊模型最簡單的方式。

+ +

而管理站則是高度用戶化的,我們會在接下來繼續說明其它註冊你的模型的方式。

+ +

創建超級用戶(Creating a superuser)

+ +

為了能夠登入管理站,我們需要一個有啟用員工狀態(Staff status)的使用者帳號,另外為了要能檢視與產生資料,我們也需要讓這個使用者帳號擁有管理所有物件的權限,因此,你可以透過 manage.py 來創建一個擁有所有網站存取權限的超級用戶(superuser)。

+ +

在與 manage.py 同一個資料夾中執行下方指令,建立一個超級用戶,你會被提示要輸入「使用者名稱」、「使用者 e-mail」和「強度夠高的密碼」。

+ +
python3 manage.py createsuperuser
+ +

當完成指令輸入後,一個新的超級用戶就會被加進資料庫中,再來只要重新啟動開發用 server ,你便可以進行登入測試:

+ +
python3 manage.py runserver
+
+ +

登入並開始使用網站

+ +

要登入網站,必須先連上  /admin URL (e.g. http://127.0.0.1:8000/admin) 並且輸入你的超級用戶的使用者名稱與密碼(你會被重新導向登入頁面,輸入你的帳密後會再回到  /admin URL)。

+ +

網站中的這部分羅列了所有以我們安裝的 app 分組的模型,你可以點擊模型名稱進入陳列所有與其相關連資料的頁面,而你可以進一步編輯它們,或者你也可以直接點擊模型名稱旁邊的 Add 連結來開始創建該類型的資料。

+ +

Admin Site - Home page

+ +

點擊 Books 右邊的 Add 連結來新增一本新書(會產生如下方的對話方塊),可以去觀察每個字段(field)、小部件、提示文字(如果有的話)是如何對應到你的模型的。

+ +

在字段中輸入值,你可以透過各個字段旁邊的 + 按鈕來新增「作者」或「書籍類別」(或者從列表中選擇你已經新增的值),當你完成後可以點選 SAVE, Save and add another, 或 Save and continue editing 來儲存該筆資料。

+ +

Admin Site - Book Add

+ +
+

注意:在這邊我們希望你花點時間在你的 app 中新增一些書本、作者和書及類型(例如:奇幻等)。請確保每位作者與每種書籍類型都分別關聯了一本以上的書(這在文章稍後的實作的時候,會讓你的列表與細節視圖更加豐富有趣)

+
+ +

當你新增完書本後,點擊上方書籤的 Home 連結回到主要管理頁面,接著點擊 Books 連結來展示目前的書本清單(你也可以點及其他連結看看其他模型的列表),現在你已經加了幾本書,畫面應該會與下方截圖類似,你可以看到下方陳列了每本書的標題,這是我們在上一篇文章所提到的 Book 模型中的 __str__() 方法所回傳的值。

+ +

Admin Site - List of book objects

+ +

在列表中,如果要刪掉你不想要的書,只需要先勾選欲刪除書本的勾選方框,從動作下拉選單選擇刪除動作(delete action),接著點選 GO 按鈕即可,另外你也可以點選 ADD BOOK 按鈕來新增一本書。

+ +

你可以點擊書名來編輯它,下方顯示的書本編輯頁面幾乎與 Add 頁面相同,主要差異在於頁面的標題(Change book)以及增加了 Delete, HISTORY 和 VIEW ON SITE 按鈕(會有這個按鈕出現是因為我們之前在模型中有定義了 get_absolute_url() 的方法)

+ +

Admin Site - Book Edit

+ +

現在透過頁面上方的索引連結回到 Home 頁面,然後看看 Author 和 Genre 列表,你在新增書本的時候應該已經新增了一些資料,不過你還可以再新增更多。

+ +

你還沒有任何書本實例(Book Instances),因為這不會在建立書本時就產生(但你可以在新增 BookInstance 資料時新增 Book  ,這是 ForeignKey 字段的性質)。現在回到 Home 頁面然後點擊 Book instances 的 Add 按鈕,畫面會呈現如下圖的頁面,注意第一列有個很長、全域唯一的 id 編碼,它可以用來區分每本書在圖書館裡的每個副本。

+ +

Admin Site - BookInstance Add

+ +

幫你的每本書都新增幾筆不同的資料,有些資料的狀態(Status)請設成 Available ,有些則設成 On loan,如果狀態為 not Available,那記得需要設定到期日(Due back date)。

+ +

就是這樣!你現在已經學會了如何建立與使用管理站(administration site),你也為你的 Book, BookInstance, Genre, 和 Author 模型建立了幾筆資料,再來當我們建立好視圖(Views)以及模板(Templates)後,就會開始來使用它們。

+ +

進階組態(Advanced configuration)

+ +

Django 在「透過註冊模型的資訊建立管理站」這方面做得非常好:

+ + + +

你可以進一步訂製介面讓它更好用,以下是你可以進一步做的:

+ + + +

這部分我們將要來看幾個有助於改善 LocalLibrary 介面的小變化,包含了添加更多資訊到 Book 和 Author 模型列表,以及改善編輯視圖的排版。我們不會改變 Language 和 Genre 的模型外貌因為他們都各只有1個字段,這樣做沒好處!

+ +

你可以在 The Django Admin site (Django Docs) 找到關於管理站訂製選擇的完整參考。

+ +

註冊一個 模型管理 類別 (ModelAdmin class)

+ +

為了要改變模型在管理站的陳列方式,你需要定義一個模型管理(ModelAdmin)類別 (他是用來描述排版的),並且將它與其他模型一起註冊。

+ +

我們現在先從 Author 模型開始。打開 catalog app 中的 admin.py 檔案(/locallibrary/catalog/admin.py),並將先前註冊 Author 模型的程式碼註解(在程式碼前面加一個 # 前綴):

+ +
# admin.site.register(Author)
+ +

現在加上一個新的 AuthorAdmin 類別與註冊函式,如下方所示:

+ +
# Define the admin class
+class AuthorAdmin(admin.ModelAdmin):
+    pass
+
+# Register the admin class with the associated model
+admin.site.register(Author, AuthorAdmin)
+
+ +

現在我們要為 Book 以及 BookInstance 模型添加 ModelAdmin 類別,我們一樣要先把原本的註冊程式碼註解:

+ +
#admin.site.register(Book)
+#admin.site.register(BookInstance)
+ +

現在我們要創造並註冊新的模型;為了達到示範的目的,我們會使用 @register 裝飾器替代先前做法來註冊模型(這跟 admin.site.register() 的語法做的事情完全一樣):

+ +
# Register the Admin classes for Book using the decorator
+@admin.register(Book)
+class BookAdmin(admin.ModelAdmin):
+    pass
+
+# Register the Admin classes for BookInstance using the decorator
+@admin.register(BookInstance)
+class BookInstanceAdmin(admin.ModelAdmin):
+    pass
+ +

目前為止我們的管理類別都是空的(可以看到 "pass"),所以我們的管理行為都不會改變!現在我們可以來進一步定義我們的「特定模型的管理行為」。

+ +

配置列表視圖(Configure list views)

+ +

我們的 LocalLibrary 目前條列出所有作者,而他們都是使用以模型的 __str__() 方法產生的物件名稱。如過你只有少數幾個作者,那倒還好,但如果作者很多,你最後可能會有非常多副本。因此為了區別他們,或者你只是想呈現更多作者的有趣訊息,你可以使用「列表展示」(list_display)來位視圖添加額外的字段。

+ +

將你的 AuthorAdmin 類別以下方程式碼取代。下方程式碼可以看出來,列表中被展示出來的字段名稱會被以需要的排序宣告為元組(tuple)形式。

+ +
class AuthorAdmin(admin.ModelAdmin):
+    list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death')
+ +

現在把網站導向作者列表,上方所設定的字段應該會被陳列出來,如下:

+ +

Admin Site - Improved Author List

+ +

至於我們的 Book 模型,我們將額外添加 author 和 genre 兩樣。author 是一個ForeignKey 外鍵字段(一對一)關係,因此他將會透過關聯紀錄的 __str__() 值來表示。

+ +

將 BookAdmin 類別以下方區段程式碼取代:

+ +
class BookAdmin(admin.ModelAdmin):
+    list_display = ('title', 'author', 'display_genre')
+ +

很不幸地,我們無法直接在 list_display 中指定「書籍類別」(genre field)字段,因為它是一個 ManyToManyField (多對多字段),因為如果這樣做會造成很大的資料庫讀寫「成本」,所以 Django 會預防這樣的狀況發生,因此,取而代之,我們將定義一個 display_genre 函式以「字串」形式得到書籍類別。(下方有定義此函式)

+ +
+

Note: Getting the genre may not be a good idea here, because of the "cost" of the database operation. We're showing you how because calling functions in your models can be very useful for other reasons — for example to add a Delete link next to every item in the list.

+
+ +

將以下程式碼添加到Book模型(models.py)。 這會從genre記錄的的頭三個值(如果有的話)創建一個字符串, 和創建一個在管理者網站中出現的short_description標題。

+ +
    def display_genre(self):
+        """Create a string for the Genre. This is required to display genre in Admin."""
+        return ', '.join(genre.name for genre in self.genre.all()[:3])
+
+    display_genre.short_description = 'Genre'
+
+ +

保存模型並更新管理員後,打開您的網站並轉到“Books”列表頁面; 您應該會看到類似以下的書籍清單:

+ +

Admin Site - Improved Book List

+ +

Genre 模型(如果定義了語言模型,則還有 Language 模型)都有一個欄位,因此沒有必要為它們創建其他模型以顯示欄位。

+ +
+

注意: 更新 BookInstance 模型列表用來顯示狀態和預期的返回日期是有價值的。 我們在本文結尾處添加了一個挑戰!

+
+ +

加入列表過濾器 (List Filter)

+ +

當你的列表有很多個記錄時, 加入列表過濾器可以幫助你過濾想顯示的記錄。加入list_filter這個屬性就可以。請用以下的程式碼來取代原本的 BookInstanceAdmin 類別

+ +
class BookInstanceAdmin(admin.ModelAdmin):
+    list_filter = ('status', 'due_back')
+
+ +

現在的列表視圖右邊會多了一個過濾器。你可以選擇 dates 和 status 來做過濾:

+ +

Admin Site - BookInstance List Filters

+ +

組織詳細視圖佈局

+ +

默認情況下,局部視圖按照模型中聲明的順序垂直排列所有字段。 您可以更改聲明的順序,顯示(或排除)哪些字段,使用分段來組織資訊,水平顯示還是垂直顯示字段,甚至管理表單中使用哪些編輯小部件。

+ +
+

注意:  LocalLibrary 模型相對簡單,因此我們無須更改佈局。 但我們仍然會進行一些更改,向您展示如何進行。

+
+ +

控制那些欄位顯示並佈置

+ +

更新你的 AuthorAdmin 類別用來新增 fields 這行,如同下列所示 (粗體):

+ +
class AuthorAdmin(admin.ModelAdmin):
+    list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death')
+    fields = ['first_name', 'last_name', ('date_of_birth', 'date_of_death')]
+
+ +

fields 屬性僅按順序列出了要在表單上顯示的那些欄位。 默認情況下,字段是垂直顯示的,但是如果您進一步將它們分組到一個元組中,它們將水平顯示(如上面的“日期”字段中所示)。

+ +

在您的網站上,轉到作者詳細信息視圖-現在應如下所示:

+ +

Admin Site - Improved Author Detail

+ +
+

注意: 您還可以使用 exclude 屬性來聲明要從表單中排除的屬性列表(將顯示模型中的所有其他屬性)。

+
+ +

Sectioning the detail view

+ +

You can add "sections" to group related model information within the detail form, using the fieldsets attribute.

+ +

In the BookInstance model we have information related to what the book is (i.e. name, imprint, and id) and when it will be available (status, due_back). We can add these in different sections by adding the text in bold to our BookInstanceAdmin class. 

+ +
@admin.register(BookInstance)
+class BookInstanceAdmin(admin.ModelAdmin):
+    list_filter = ('status', 'due_back')
+
+    fieldsets = (
+        (None, {
+            'fields': ('book', 'imprint', 'id')
+        }),
+        ('Availability', {
+            'fields': ('status', 'due_back')
+        }),
+    )
+ +

Each section has its own title (or None, if you don't want a title) and an associated tuple of fields in a dictionary — the format is complicated to describe, but fairly easy to understand if you look at the code fragment immediately above.

+ +

Now navigate to a book instance view in your website; the form should appear as shown below:

+ +

Admin Site - Improved BookInstance Detail with sections

+ +

Inline editing of associated records

+ +

Sometimes it can make sense to be able to add associated records at the same time. For example, it may make sense to have both the book information and information about the specific copies you've got on the same detail page.

+ +

You can do this by declaring inlines, of type TabularInline (horizonal layout) or StackedInline (vertical layout, just like the default model layout). You can add the BookInstance information inline to our Book detail by adding the lines below in bold near your BookAdmin:

+ +
class BooksInstanceInline(admin.TabularInline):
+    model = BookInstance
+
+@admin.register(Book)
+class BookAdmin(admin.ModelAdmin):
+    list_display = ('title', 'author', 'display_genre')
+    inlines = [BooksInstanceInline]
+
+ +

Now navigate to a view for a Book in your website — at the bottom you should now see the book instances relating to this book (immediately below the book's genre fields):

+ +

Admin Site - Book with Inlines

+ +

In this case all we've done is declare our tabular inline class, which just adds all fields from the inlined model. You can specify all sorts of additional information for the layout, including the fields to display, their order, whether they are read only or not,  etc. (see TabularInline for more information). 

+ +
+

Note: There are some painful limits in this functionality! In the screenshot above we have three existing book instances, followed by three placeholders for new book instances (which look very similar!). It would be better to have NO spare book instances by default and just add them with the Add another Book instance link, or to be able to just list the BookInstances as non-readable links from here. The first option can be done by setting the extra attribute to 0 in BooksInstanceInline model, try it by yourself.

+
+ +

自我挑戰

+ +

在本節中我們學到了很多東西,所以現在該您嘗試一些事情了。

+ +
    +
  1. 對於BookInstance列表視圖(list view),添加代碼以顯示booksstatusdue back dateid(而不是默認的__str __()文本)。
  2. +
  3. 使用與Book/BookInstance相同的方法將Book項目的內聯列表添加到Author 的詳細視圖(detail view)中。
  4. +
+ + + +

小結

+ +

就是這樣! 您現在已經了解瞭如何以最簡單和改進的形式設置管理者網站,如何創建超級用戶,以及如何瀏覽管理者網站,查看,刪除和更新記錄。 在此過程中,您已經創建了許多Books,BookInstances,Genres和Authors,一旦我們創建了自己的view和templates,便可以列出和顯示這些記錄。

+ +

延伸閱讀

+ + + +

{{PreviousMenuNext("Learn/Server-side/Django/Models", "Learn/Server-side/Django/Home_page", "Learn/Server-side/Django")}}

+ +

In this module

+ + diff --git a/files/zh-tw/learn/server-side/django/authentication/index.html b/files/zh-tw/learn/server-side/django/authentication/index.html new file mode 100644 index 0000000000..ec15ddeffd --- /dev/null +++ b/files/zh-tw/learn/server-side/django/authentication/index.html @@ -0,0 +1,698 @@ +--- +title: 'Django Tutorial Part 8: User authentication and permissions' +slug: Learn/Server-side/Django/Authentication +translation_of: Learn/Server-side/Django/Authentication +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Django/Sessions", "Learn/Server-side/Django/Forms", "Learn/Server-side/Django")}}
+ +

在本教程中,我們將會展示如何允許用戶使用自己的帳戶登入到您的網站,以及如何根據用戶是否已登入和權限的不同來控制他們可以執行和查看的內容。作為展示的一部分,我們會擴展 LocalLibrary 網站,添加登入頁面和登出頁面,以及用來查看已借閱的圖書的頁面 - 分為用戶與員工兩種不同頁面。

+ + + + + + + + + + + + +
前提:完成至 Django 線上教學 7: 會話(Sessions)框架為止的所有主題。
目標:了解如何設定與運用使用者驗證與權限機制。
+ +

大綱

+ +

Django提供認證和授權(“ permission”)系統,該系統建立在上一教程中討論的會話框架的基礎上。透過它可以驗證用戶憑證並定義個別用戶能夠執行的操作。 該框架包括用於UsersGroups 的內置模型(一般常用來一次性套用權限於一群用戶上的方式),用於指定用戶是否可以執行任務的權限/旗標,用於登入用戶的表單和視圖,以及 查看用於限制內容的工具。

+ +
+

注意: 從Django角度而言,身份驗證系統需要做到非常通用,因此不提供其他網頁身份驗證系統中提供的某些功能。 需要解決一些常見問題的話可以透過第三方軟件包。 例如,限制登錄嘗試和透過第三方進行身份驗證(例如OAuth)。

+
+ +

在本教程中,我們將會展示如何在LocalLibrary網站中啟用用戶身份驗證,並建立自己的登入和登出頁面,為模型添加權限以及控制對頁面的訪問。 我們將根據身份驗證/權限顯示為用戶或是圖書館員設計的已借出書籍列表。

+ +

身份驗證系統非常有彈性,您可以根據需要從頭開始構建URL,表單,視圖和模板,只透過提供的API來登入用戶。 但是,在本文中,我們將為登入與登出頁面使用Django的“ stock”身份驗證視圖和表單。 我們仍然需要建立一些模板,但這很簡單。

+ +

我們還將向您展示如何建立權限,並在視圖和模板中檢查登入狀態和權限。

+ +

Enabling authentication

+ +

當我們創建框架網站時(在教程2中),身份驗證已自動啟用,因此您此時無需執行任何其他操作。

+ +
+

注意: 當我們使用django-admin startproject命令創建應用程序時,所有必要的配置都為我們完成了。 用戶和模型權限的數據庫表是在我們首次調用python manage.py migrate時創建的。

+
+ +

該配置是在項目文件(locallibrary/locallibrary/settings.py)的INSTALLED_APPSMIDDLEWARE 部分中設置的,如下所示:

+ +
INSTALLED_APPS = [
+    ...
+    'django.contrib.auth',  #Core authentication framework and its default models.
+    'django.contrib.contenttypes',  #Django content type system (allows permissions to be associated with models).
+    ....
+
+MIDDLEWARE = [
+    ...
+    'django.contrib.sessions.middleware.SessionMiddleware',  #Manages sessions across requests
+    ...
+    'django.contrib.auth.middleware.AuthenticationMiddleware',  #Associates users with requests using sessions.
+    ....
+
+ +

Creating users and groups

+ +

當我們在教程4中查看Django管理站點時,您已經創建了第一個用戶(這是一個超級用戶,使用命令ppython manage.py createsuperuser創建)。 我們的超級用戶已經通過身份驗證,並且具有所有權限,因此我們需要創建一個測試用戶來代表普通站點用戶。 我們將使用管理站點來創建本地圖書館組和網站登錄名,因為這是最快的方法之一。

+ +
+

注意: 您還可以通過編程方式創建用戶,如下所示。 例如,如果要開發一個界面以允許用戶創建自己的登錄名,則必須這樣做(您不應授予用戶訪問管理站點的權限)。

+ +
from django.contrib.auth.models import User
+
+# Create user and save to the database
+user = User.objects.create_user('myusername', 'myemail@crazymail.com', 'mypassword')
+
+# Update fields and then save again
+user.first_name = 'John'
+user.last_name = 'Citizen'
+user.save()
+
+
+ +

在下面,我們將首先創建一個組,然後創建一個用戶。 即使我們還沒有添加庫成員的任何權限,但是如果以後需要添加,將它們一次添加到組中要比分別添加到每個成員要容易得多。

+ +

啟動開發服務器,然後在本地Web瀏覽器(http://127.0.0.1:8000/admin/)中導航到管理站點。 使用您的超級用戶帳戶的憑據登錄到該站點。 管理站點的頂層顯示所有模型,按“ django應用程序”排序。 在“Authentication and Authorisation”部分,您可以單擊Users 或Groups鏈接以查看其現有記錄。

+ +

Admin site - add groups or users

+ +

首先,讓我們為圖書館成員創建一個新組。

+ +
    +
  1. 單擊Add按鈕(在組旁邊)以創建一個新組; 輸入該組的名稱“Library Members”。
    + Admin site - add group
  2. +
  3. 我們不需要該組的任何權限,因此只需按SAVE (您將被帶到組列表)。
  4. +
+ +

現在讓我們創建一個用戶:

+ +
    +
  1. 導航回到管理站點的主頁
  2. +
  3. 單擊“用戶”旁邊的“添加”按鈕以打開“添加用戶”對話框。
    + Admin site - add user pt1
  4. +
  5. 輸入適合您的測試用戶的用戶名和密碼/密碼確認
  6. +
  7. SAVE創建用戶。
    + 管理站點將創建新用戶,並立即將您帶到“更改用戶”視窗,您可以在其中更改用戶名並為用戶模型的可選字段添加信息。 這些字段包括名字,姓氏,電子郵件地址,用戶狀態和權限(僅應設置“活動”標誌)。 在更下方的位置,您可以指定用戶的組和權限,並查看與該用戶相關的重要日期(例如,他們的加入日期和上次登錄日期)。
    + Admin site - add user pt2
  8. +
  9. 在“組”部分中,從“可用組”列表中選擇“Library Member”組,然後按框之間的右箭頭將其移至“選擇的組”框中。Admin site - add user to group
  10. +
  11. 我們在這裡不需要執行任何其他操作,因此只需再次選擇SAVE 即可進入用戶列表。
  12. +
+ +

就是這樣而已! 現在,您將擁有一個“普通庫成員”帳戶,您將可以使用該帳戶進行測試(一旦我們實現了頁面以使其能夠登錄)。

+ +
+

注意:您應該嘗試創建另一個庫成員用戶。 另外,為圖書館員創建一個組,並為其添加用戶!

+
+ +

Setting up your authentication views

+ +

Django提供了創建身份驗證頁面所需的幾乎所有內容,以處理“開箱即用”的登錄,註銷和密碼管理。 這包括URL映射器,視圖和表單,但不包括模板-我們必須創建自己的模板!

+ +

在本節中,我們顯示如何將默認系統集成到LocalLibrary網站中並創建模板。 我們將它們放在主項目URL中。

+ +
+

注意: 您不必使用任何代碼,但是您可能想要使用它,因為它使事情變得容易得多。 如果您更改用戶模型(一個高級主題!),幾乎可以肯定需要更改表單處理代碼,但是即使如此,您仍然可以使用庫存視圖功能。

+
+ +
+

注意: 在這種情況下,我們可以合理地將身份驗證頁面(包括URL和模板)放入目錄應用程序中。 但是,如果我們有多個應用程序,最好將這種共享的登錄行為分開,並使其在整個站點中都可用,這就是我們在此處顯示的內容!

+
+ +

Project URLs

+ +

將以下內容添加到項目urls.py文件(locallibrary/locallibrary/urls.py)文件的底部:

+ +
#Add Django site authentication urls (for login, logout, password management)
+urlpatterns += [
+    path('accounts/', include('django.contrib.auth.urls')),
+]
+
+ +

導航到http://127.0.0.1:8000/accounts/ URL(注意尾隨斜杠!),然後Django將顯示一個錯誤,指出找不到此URL,並列出了它嘗試的所有URL。 從中您可以看到將起作用的URL,例如:

+ +
+

注意: 使用上述方法會在方括號中添加以下網址,這些網址可用於反轉網址映射。 您無需執行其他任何操作-上面的url映射會自動映射以下提到的URL。

+
+ +
+
accounts/ login/ [name='login']
+accounts/ logout/ [name='logout']
+accounts/ password_change/ [name='password_change']
+accounts/ password_change/done/ [name='password_change_done']
+accounts/ password_reset/ [name='password_reset']
+accounts/ password_reset/done/ [name='password_reset_done']
+accounts/ reset/<uidb64>/<token>/ [name='password_reset_confirm']
+accounts/ reset/done/ [name='password_reset_complete']
+
+ +

現在嘗試導航到登錄URL(http://127.0.0.1:8000/accounts/login/)。 這將再次失敗,但是會顯示一條錯誤消息,告訴您我們在模板搜索路徑上缺少必需的模板(registration/login.html)。 您會在頂部黃色部分看到以下幾行:

+ +
Exception Type:    TemplateDoesNotExist
+Exception Value:    registration/login.html
+ +

下一步是在搜索路徑上創建註冊目錄,然後添加login.html文件。

+ +

Template directory

+ +

我們剛剛添加的url(和隱式視圖)期望在模板搜索路徑中某個目錄/registration/ 中找到它們的關聯模板。

+ +

對於這個網站,我們將HTML頁面放在templates/registration/目錄中。 此目錄應位於您的項目根目錄中,即與cataloglocallibrary 文件夾相同的目錄中)。 請立即創建這些文件夾。

+ +
+

Note: Your folder structure should now look like the below:
+ locallibrary (django project folder)
+    |_catalog
+    |_locallibrary
+    |_templates (new)
+                 |_registration

+
+ +

為了使這些目錄對模板加載器可見(即將該目錄放置在模板搜索路徑中),請打開項目設置(/locallibrary/locallibrary/settings.py),並更新TEMPLATES 部分的DIRS行,如圖所示。

+ +
TEMPLATES = [
+    {
+        ...
+        'DIRS': ['./templates',],
+        'APP_DIRS': True,
+        ...
+
+ +

Login template

+ +
+

重要信息:本文提供的身份驗證模板是Django演示登錄模板的非常基本/稍作修改的版本。 您可能需要自定義它們以供自己使用!

+
+ +

創建一個名為/locallibrary/templates/registration/login.html的新HTML文件。 為其提供以下內容:

+ +
{% extends "base_generic.html" %}
+
+{% block content %}
+
+{% if form.errors %}
+  <p>Your username and password didn't match. Please try again.</p>
+{% endif %}
+
+{% if next %}
+  {% if user.is_authenticated %}
+    <p>Your account doesn't have access to this page. To proceed,
+    please login with an account that has access.</p>
+  {% else %}
+    <p>Please login to see this page.</p>
+  {% endif %}
+{% endif %}
+
+<form method="post" action="{% url 'login' %}">
+{% csrf_token %}
+
+<div>
+  <td>\{{ form.username.label_tag }}</td>
+  <td>\{{ form.username }}</td>
+</div>
+<div>
+  <td>\{{ form.password.label_tag }}</td>
+  <td>\{{ form.password }}</td>
+</div>
+
+<div>
+  <input type="submit" value="login" />
+  <input type="hidden" name="next" value="\{{ next }}" />
+</div>
+</form>
+
+{# Assumes you setup the password_reset view in your URLconf #}
+<p><a href="{% url 'password_reset' %}">Lost password?</a></p>
+
+{% endblock %}
+ +

該模板與我們之前看到的模板有一些相似之處-它擴展了我們的基本模板並覆蓋了內容塊。 其餘代碼是相當標準的表單處理代碼,我們將在以後的教程中進行討論。 現在您只需要知道的是,這將顯示一個表格,您可以在其中輸入用戶名和密碼,並且如果輸入無效的值,則在頁面刷新時會提示您輸入正確的值。

+ +

保存模板後,導航回到登錄頁面(http://127.0.0.1:8000/accounts/login/),您應該看到類似以下內容:

+ +

Library login page v1

+ +

如果嘗試登錄將成功,並且您將被重定向到另一個頁面(默認情況下為http://127.0.0.1:8000/accounts/profile/)。 這裡的問題是,默認情況下,Django期望登錄後將您帶到個人資料頁面,情況可能與否。 由於您尚未定義此頁面,因此會出現另一個錯誤!

+ +

打開項目設置(/locallibrary/locallibrary/settings.py) ,然後將下面的文本添加到底部。 現在,當您登錄時,默認情況下應將您重定向到網站主頁。

+ +
# Redirect to home URL after login (Default redirects to /accounts/profile/)
+LOGIN_REDIRECT_URL = '/'
+
+ +

Logout template

+ +

如果您導航到登出URL (http://127.0.0.1:8000/accounts/logout/) ,則會看到一些奇怪的行為-您的用戶將被確定地註銷,但是您將被帶到Admin 註銷頁面。 那不是您想要的,僅僅是因為該頁面上的登錄鏈接將您帶到Admin 登錄屏幕(並且僅對具有is_staff 權限的用戶可用)。

+ +

創建並打開 /locallibrary/templates/registration/logged_out.html。 複製以下文本:

+ +
{% extends "base_generic.html" %}
+
+{% block content %}
+  <p>Logged out!</p>
+  <a href="{% url 'login'%}">Click here to login again.</a>
+{% endblock %}
+ +

這個模板非常簡單。 它僅顯示一條消息,通知您已註銷,並提供一個鏈接,您可以按此鏈接返回登錄屏幕。 如果再次進入註銷URL,您應該看到以下頁面:

+ +

Library logout page v1

+ +

Password reset templates

+ +

默認的密碼重置系統使用電子郵件向用戶發送重置鏈接。 您需要創建表格以獲取用戶的電子郵件地址,發送電子郵件,允許他們輸入新密碼並在整個過程完成時註明。

+ +

以下模板可以用作起點。

+ +

密碼重設表格

+ +

這是用於獲取用戶電子郵件地址(用於發送密碼重置電子郵件)的表格。 創建/locallibrary/templates/registration/password_reset_form.html,並為其提供以下內容:

+ +
{% extends "base_generic.html" %}
+
+{% block content %}
+  <form action="" method="post">
+  {% csrf_token %}
+  {% if form.email.errors %}
+    {{ form.email.errors }}
+  {% endif %}
+      <p>\{{ form.email }}</p>
+    <input type="submit" class="btn btn-default btn-lg" value="Reset password">
+  </form>
+{% endblock %}
+
+ +

密碼重置完成

+ +

收集您的電子郵件地址後,將顯示此表單。創建 /locallibrary/templates/registration/password_reset_done.html,並為其提供以下內容:

+ +
{% extends "base_generic.html" %}
+
+{% block content %}
+  <p>We've emailed you instructions for setting your password. If they haven't arrived in a few minutes, check your spam folder.</p>
+{% endblock %}
+
+ +

密碼重置電子郵件

+ +

該模板提供了HTML電子郵件的文本,其中包含我們將發送給用戶的重置鏈接。 創建/locallibrary/templates/registration/password_reset_email.html,並為其提供以下內容:

+ +
Someone asked for password reset for email \{{ email }}. Follow the link below:
+\{{ protocol}}://\{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}
+
+ +

密碼重置確認

+ +

單擊密碼重置電子郵件中的鏈接後,即可在此頁面輸入新密碼。 創建 /locallibrary/templates/registration/password_reset_confirm.html,並為其提供以下內容:

+ +
{% extends "base_generic.html" %}
+
+{% block content %}
+    {% if validlink %}
+        <p>Please enter (and confirm) your new password.</p>
+        <form action="" method="post">
+            <div style="display:none">
+                <input type="hidden" value="\{{ csrf_token }}" name="csrfmiddlewaretoken">
+            </div>
+            <table>
+                <tr>
+                    <td>\{{ form.new_password1.errors }}
+                        <label for="id_new_password1">New password:</label></td>
+                    <td>\{{ form.new_password1 }}</td>
+                </tr>
+                <tr>
+                    <td>\{{ form.new_password2.errors }}
+                        <label for="id_new_password2">Confirm password:</label></td>
+                    <td>\{{ form.new_password2 }}</td>
+                </tr>
+                <tr>
+                    <td></td>
+                    <td><input type="submit" value="Change my password" /></td>
+                </tr>
+            </table>
+        </form>
+    {% else %}
+        <h1>Password reset failed</h1>
+        <p>The password reset link was invalid, possibly because it has already been used. Please request a new password reset.</p>
+    {% endif %}
+{% endblock %}
+
+ +

密碼重置完成

+ +

這是最後一個密碼重設模板,密碼重設成功後將顯示此模板以通知您。 創建/locallibrary/templates/registration/password_reset_complete.html,並為其提供以下內容:

+ +
{% extends "base_generic.html" %}
+
+{% block content %}
+  <h1>The password has been changed!</h1>
+  <p><a href="{% url 'login' %}">log in again?</a></p>
+{% endblock %}
+ +

Testing the new authentication pages

+ +

現在您已經添加了URL配置並創建了所有這些模板,身份驗證頁面現在應該可以正常工作了!

+ +

您可以通過嘗試使用以下URL登錄然後註銷超級用戶帳戶來測試新的身份驗證頁面:

+ + + +

您可以通過登錄頁面中的鏈接測試密碼重置功能。 請注意,Django只會將重置電子郵件發送到已經存儲在其數據庫中的地址(用戶)!

+ +
+

筆記:密碼重設系統要求您的網站支持電子郵件,這不在本文的討論範圍之內,因此該部分尚無法使用。 要進行測試,請將以下行放在settings.py文件的末尾。 這將記錄發送到控制台的所有電子郵件(因此您可以從控制台複製密碼重置鏈接)。

+ +
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
+
+ +

有關更多信息,請參閱發送電子郵件(Sending emailDjango文檔)。

+
+ +

針對經過身份驗證的用戶進行測試

+ +

本節介紹如何根據用戶是否登錄來有選擇地控制用戶看到的內容。

+ +

在模板中測試

+ +

您可以使用 \{{ user }}模板變量在模板中獲取有關當前登錄用戶的信息(默認情況下,就像我們在框架中一樣設置項目時,該信息會添加到模板上下文中)。

+ +

通常,您將首先針對 \{{ user.is_authenticated }}模板變量進行測試,以確定該用戶是否有資格查看特定內容。 為了演示這一點,接下來,我們將更新邊欄,以在用戶註銷時顯示“登錄”鏈接,在用戶登錄時顯示“註銷”鏈接。

+ +

打開基礎模板。 (/locallibrary/catalog/templates/base_generic.html) ,然後將以下文本複製到sidebar 塊中,緊接在endblock 模板標籤之前。

+ +
  <ul class="sidebar-nav">
+
+    ...
+
+   {% if user.is_authenticated %}
+     <li>User: \{{ user.get_username }}</li>
+     <li><a href="{% url 'logout'%}?next=\{{request.path}}">Logout</a></li>
+   {% else %}
+     <li><a href="{% url 'login'%}?next=\{{request.path}}">Login</a></li>
+   {% endif %} 
+  </ul>
+ +

如您所見,我們使用 if-else-endif 模板標籤根據 \{{ user.is_authenticated }} \ {{user.is_authenticated}}是否為真來有條件地顯示文本。 如果用戶通過了身份驗證,那麼我們知道我們有一個有效的用戶,因此我們調用 \{{ user.get_username }} 來顯示其名稱。

+ +

我們使用url 模板標記和相應URL配置的名稱來創建登錄和註銷鏈接URL。 還要注意我們如何將?next=\{{request.path}}附加到URL的末尾。 這是在鏈接的URL的末尾添加一個URL參數,其中包含當前頁面的地址(URL)。 用戶成功登錄/註銷後,視圖將使用此``next''值將用戶重定向到他們首先單擊 login/logout 鏈接的頁面。

+ +
+

注意:試試看! 如果您在主頁上,然後單擊側欄中的“Login/Logout”,那麼在操作完成後,您應該回到同一頁面。

+
+ +

在視圖中測試

+ +

如果您使用的是基於函數的視圖,則限制訪問函數的最簡單方法是將login_required 裝飾器應用於視圖函數,如下所示。 如果用戶已登錄,則您的視圖代碼將正常執行。 如果用戶未登錄,它將重定向到項目設置(settings.LOGIN_URL)中定義的登錄URL,並將當前的絕對路徑作為next URL參數傳遞。 如果用戶成功登錄,則他們將返回此頁面,但這次已通過身份驗證。

+ +
from django.contrib.auth.decorators import login_required
+
+@login_required
+def my_view(request):
+    ...
+ +
+

注意: 您可以通過在request.user.is_authenticated上進行測試來手動執行相同的操作,但是裝飾器要方便得多!

+
+ +

同樣,在基於類的視圖中限制對登錄用戶的訪問權限的最簡單方法是從 LoginRequiredMixin. 派生。 您需要首先在父類列表中,在主視圖類之前聲明此混合。

+ +
from django.contrib.auth.mixins import LoginRequiredMixin
+
+class MyView(LoginRequiredMixin, View):
+    ...
+ +

它具有與 login_required 裝飾器完全相同的重定向行為。 如果用戶未通過身份驗證,也可以指定其他位置來重定向用戶 (login_url),並使用URL參數名稱代替“ next”來插入當前的絕對路徑(redirect_field_name).。

+ +
class MyView(LoginRequiredMixin, View):
+    login_url = '/login/'
+    redirect_field_name = 'redirect_to'
+
+ +

有關更多詳細信息,請在此處查看Django文檔

+ +

範例—列出當前用戶的書籍

+ +

現在,我們知道瞭如何將頁面限制為特定用戶,讓我們創建當前用戶借閱的書籍的視圖。

+ +

不幸的是,我們還沒有任何方式讓用戶借書! 因此,在創建圖書清單之前,我們將首先擴展BookInstance 模型以支持借用的概念,並使用Django Admin應用程序將大量圖書借給我們的測試用戶。

+ +

模型

+ +

首先,我們將必須使用戶可以藉用BookInstance (我們已經具有statusdue_back ,但是在該模型和User之間還沒有任何關聯。我們將創建 一個使用ForeignKey (一對多)字段的方法,我們還需要一種簡單的機制來測試借出的書是否過期。
+
+ 打開catalog/models.py,然後從 django.contrib.auth.models導入User 模型(將其添加到文件頂部的前一個導入行下面,因此User 可供使用它的後續代碼使用):

+ +
from django.contrib.auth.models import User
+
+ +

Ne接下來,將borrower 字段添加到BookInstance 模型中:

+ +
borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
+
+ +

當我們在這裡時,讓我們添加一個屬性,我們可以從模板中調用該屬性,以告知特定的圖書實例是否過期。 儘管我們可以在模板本身中進行計算,但是使用如下所示的屬性會更加高效。

+ +

將此添加到文件頂部附近:

+ +
from datetime import date
+ +

現在,在BookInstance類中添加以下屬性定義:

+ +
@property
+def is_overdue(self):
+    if self.due_back and date.today() > self.due_back:
+        return True
+    return False
+ +
+

Note: 在進行比較之前,我們首先要驗證due_back是否為空。 空的 due_back字段將導致Django拋出錯誤而不是顯示頁面:空值不可比。 這不是我們希望用戶體驗的東西!

+
+ +

現在,我們已經更新了模型,我們需要在項目上進行新的遷移,然後應用這些遷移:

+ +
python3 manage.py makemigrations
+python3 manage.py migrate
+
+ +

Admin

+ +

現在打開catalog/admin.py,然後將list_displayfieldsets 中的borrower 字段添加到BookInstanceAdmin 類中,如下所示。 這將使該字段在“管理”部分中可見,以便我們可以在需要時將User 分配給BookInstance

+ +
@admin.register(BookInstance)
+class BookInstanceAdmin(admin.ModelAdmin):
+    list_display = ('book', 'status', 'borrower', 'due_back', 'id')
+    list_filter = ('status', 'due_back')
+
+    fieldsets = (
+        (None, {
+            'fields': ('book','imprint', 'id')
+        }),
+        ('Availability', {
+            'fields': ('status', 'due_back','borrower')
+        }),
+    )
+ +

Loan a few books

+ +

現在可以將書借給特定用戶了,然後借出許多BookInstance 記錄。 將他們的borrowed 字段設置為測試用戶,status 為“借用”,並設置將來和將來的到期日。

+ +
+

注意:我們不會詳細說明該過程,因為您已經知道如何使用管理網站!

+
+ +

On loan view

+ +

現在,我們將添加一個視圖,以獲取已借給當前用戶的所有書籍的列表。 我們將使用我們熟悉的相同的通用的基於類的列表視圖,但是這次我們還將導入並從LoginRequiredMixin派生,以便只有登錄的用戶才能調用此視圖。 我們還將選擇聲明template_name,而不使用默認值,因為我們最終可能會擁有一些不同的BookInstance記錄列表,並具有不同的視圖和模板。
+
+ 將以下內容添加到catalog / views.py

+ +
from django.contrib.auth.mixins import LoginRequiredMixin
+
+class LoanedBooksByUserListView(LoginRequiredMixin,generic.ListView):
+    """Generic class-based view listing books on loan to current user."""
+    model = BookInstance
+    template_name ='catalog/bookinstance_list_borrowed_user.html'
+    paginate_by = 10
+
+    def get_queryset(self):
+        return BookInstance.objects.filter(borrower=self.request.user).filter(status__exact='o').order_by('due_back')
+ +

為了將查詢限制為僅針對當前用戶的BookInstance 對象,我們重新實現了 get_queryset(),如上所示。 請注意,“ o”是“借出”的存儲代碼,我們在due_back 日期之前訂購,以便最先顯示最早的項目。

+ +

URL conf for on loan books

+ +

現在打開/catalog/urls.py並添加指向上面視圖的path()(您可以將下面的文本複製到文件末尾)。

+ +
urlpatterns += [
+    path('mybooks/', views.LoanedBooksByUserListView.as_view(), name='my-borrowed'),
+]
+ +

Template for on loan books

+ +

現在,我們需要為此頁面添加模板。 首先,創建模板文件 /catalog/templates/catalog/bookinstance_list_borrowed_user.html 並為其提供以下內容:

+ +
{% extends "base_generic.html" %}
+
+{% block content %}
+    <h1>Borrowed books</h1>
+
+    {% if bookinstance_list %}
+    <ul>
+
+      {% for bookinst in bookinstance_list %}
+      <li class="{% if bookinst.is_overdue %}text-danger{% endif %}">
+        <a href="{% url 'book-detail' bookinst.book.pk %}">\{{bookinst.book.title}}</a> (\{{ bookinst.due_back }})
+      </li>
+      {% endfor %}
+    </ul>
+
+    {% else %}
+      <p>There are no books borrowed.</p>
+    {% endif %}
+{% endblock %}
+ +

該模板與我們先前為BookAuthor 物件創建的模板非常相似。 這裡唯一的“新內容”是我們檢查在模型中添加的方法(bookinst.is_overdue),並使用它來更改過期項目的顏色。

+ +

開發服務器運行時,現在應該可以在瀏覽器中的 http://127.0.0.1:8000/catalog/mybooks/ 上查看已登錄用戶的列表。 在您的用戶登錄和註銷後進行嘗試(在第二種情況下,應將您重定向到登錄頁面)。

+ +

Add the list to the sidebar

+ +

最後一步是將此新頁面的鏈接添加到側欄中。 我們將其放在同一部分中,在該部分中為登錄用戶顯示其他信息。

+ +

打開基本模板 (/locallibrary/catalog/templates/base_generic.html) 並將粗體顯示的行添加到側邊欄中,如圖所示。

+ +
 <ul class="sidebar-nav">
+   {% if user.is_authenticated %}
+   <li>User: \{{ user.get_username }}</li>
+   <li><a href="{% url 'my-borrowed' %}">My Borrowed</a></li>
+   <li><a href="{% url 'logout'%}?next=\{{request.path}}">Logout</a></li>
+   {% else %}
+   <li><a href="{% url 'login'%}?next=\{{request.path}}">Login</a></li>
+   {% endif %}
+ </ul>
+
+ +

What does it look like?

+ +

當任何用戶登錄後,他們將在邊欄中看到“My Borrowed ”,並且書的列表顯示如下(第一本書沒有截止日期,這是我們希望在以後的教程中解決的錯誤!) 。

+ +

Library - borrowed books by user

+ +

Permissions

+ +

權限與模型相關聯,並定義了具有權限的用戶可以在模型實例上執行的操作。 默認情況下,Django會自動為所有模型賦予添加,更改和刪除權限,從而允許具有權限的用戶通過管理站點執行關聯的操作。 您可以定義自己的模型權限,並將其授予特定用戶。 您還可以更改與同一模型的不同實例關聯的權限。

+ +

這樣,對視圖和模板中的權限進行的測試就非常類似於對身份驗證狀態的測試(實際上,對權限的測試也對身份驗證進行了測試)。

+ +

Models

+ +

使用permissions 字段在模型“class Meta”部分中完成權限的定義。 您可以在元組中根據需要指定任意數量的權限,每個權限本身都在嵌套的元組中定義,其中包含權限名稱和權限顯示值。 例如,我們可以定義一個權限,以允許用戶標記已退回一本書,如下所示:

+ +
class BookInstance(models.Model):
+    ...
+    class Meta:
+        ...
+        permissions = (("can_mark_returned", "Set book as returned"),)   
+ +

然後,我們可以將權限分配給管理站點中的“圖書管理員”組。

+ +

打開catalog/models.py,然後添加權限,如上所示。 您將需要重新運行遷移(調用 python3 manage.py makemigrationspython3 manage.py migrate)以適當地更新數據庫。

+ +

模板

+ +

當前用戶的權限存儲在名為 \{{ perms }}. 的模板變量中。 您可以使用關聯的Django "app"“應用”中的特定變量名稱來檢查當前用戶是否具有特定權限,例如 如果用戶具有此權限,則 \{{ perms.catalog.can_mark_returned }} 將為 True ,否則為False。 我們通常使用模板 {% if %} 標籤測試權限,如下所示:

+ +
{% if perms.catalog.can_mark_returned %}
+    <!-- We can mark a BookInstance as returned. -->
+    <!-- Perhaps add code to link to a "book return" view here. -->
+{% endif %}
+
+ +

視圖

+ +

可以在功能視圖中使用permission_required 裝飾器來測試權限,或者在基於類的視圖中使用PermissionRequiredMixin. 來測試權限。 模式和行為與登錄身份驗證的模式和行為相同,儘管當然您可能必須合理地添加多個權限。

+ +

視圖裝飾器函數:

+ +
from django.contrib.auth.decorators import permission_required
+
+@permission_required('catalog.can_mark_returned')
+@permission_required('catalog.can_edit')
+def my_view(request):
+    ...
+ +

基於類的視圖需要權限的混合。

+ +
from django.contrib.auth.mixins import PermissionRequiredMixin
+
+class MyView(PermissionRequiredMixin, View):
+    permission_required = 'catalog.can_mark_returned'
+    # Or multiple permissions
+    permission_required = ('catalog.can_mark_returned', 'catalog.can_edit')
+    # Note that 'catalog.can_edit' is just an example
+    # the catalog application doesn't have such permission!
+ +

範例

+ +

我們不會在這裡更新LocalLibrary; 也許在下一個教程中!

+ +

挑戰自己

+ +

在本文的前面,我們向您展示瞭如何為當前用戶創建一個頁面,列出他們所借用的書。 現在的挑戰是創建一個僅對圖書館員可見的相似頁面,該頁面顯示所有已借書的書,其中包括每個借書人的名字。

+ +

您應該能夠遵循與其他視圖相同的模式。 主要區別在於您只需要將視圖限制為圖書館員即可。 您可以根據用戶是否是工作人員來執行此操作(函數裝飾器:staff_member_required,模板變量: user.is_staff),但是我們建議您改用can_mark_returned 權限和PermissionRequiredMixin,如上一節所述。

+ +
+

重要:請記住不要將您的超級用戶用於基於權限的測試(即使尚未定義權限,權限檢查也始終對超級用戶返回true!)。 而是創建一個圖書管理員用戶,並添加所需的功能。

+
+ +

完成後,您的頁面應類似於以下屏幕截圖。All borrowed books, restricted to librarian

+ + + +

總結

+ +

出色的工作-您現在已經創建了一個網站,圖書館成員可以登錄並查看他們自己的內容,館員(具有正確的權限)可以用來查看所有借出的書及其借書人。 目前,我們仍在查看內容,但是當您要開始修改和添加數據時,將使用相同的原理和技術。

+ +

在下一篇文章中,我們將研究如何使用Django表單來收集用戶輸入,然後開始修改一些存儲的數據。

+ +

也可以看看

+ + + +

{{PreviousMenuNext("Learn/Server-side/Django/Sessions", "Learn/Server-side/Django/Forms", "Learn/Server-side/Django")}}

+ +

In this module

+ + diff --git a/files/zh-tw/learn/server-side/django/deployment/index.html b/files/zh-tw/learn/server-side/django/deployment/index.html new file mode 100644 index 0000000000..752714dabb --- /dev/null +++ b/files/zh-tw/learn/server-side/django/deployment/index.html @@ -0,0 +1,675 @@ +--- +title: 'Django Tutorial Part 11: Deploying Django to production' +slug: Learn/Server-side/Django/Deployment +translation_of: Learn/Server-side/Django/Deployment +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Django/Testing", "Learn/Server-side/Django/web_application_security", "Learn/Server-side/Django")}}
+ +

現在,您已經創建(並測試)了一個令人敬畏的 LocalLibrary 網站,如果您希望將其安裝在公共 Web 服務器上,以便圖書館工作人員、和成員,可以通過 Internet 訪問它。本文概述如何找到主機來部署您的網站,以及您需要做什麼,才能讓您的網站準備好生產環境。

+ + + + + + + + + + + + +
Prerequisites:Complete all previous tutorial topics, including Django Tutorial Part 10: Testing a Django web application.
Objective:To learn where and how you can deploy a Django app to production.
+ +

Overview

+ +

Once your site is finished (or finished "enough" to start public testing) you're going to need to host it somewhere more public and accessible than your personal development computer.

+ +

Up to now you've been working in a development environment, using the Django development web server to share your site to the local browser/network, and running your website with (insecure) development settings that expose debug and other private information. Before you can host a website externally you're first going to have to:

+ + + +

This tutorial provides some guidance on your options for choosing a hosting site, a brief overview of what you need to do in order to get your Django app ready for production, and a worked example of how to install the LocalLibrary website onto the Heroku cloud hosting service.

+ +

What is a production environment?

+ +

The production environment is the environment provided by the server computer where you will run your website for external consumption. The environment includes:

+ + + +
+

Note: Depending on how your production is configured you might also have a reverse proxy, load balancer, etc.

+
+ +

The server computer could be located on your premises and connected to the Internet by a fast link, but it is far more common to use a computer that is hosted "in the cloud". What this actually means is that your code is run on some remote computer (or possibly a "virtual" computer) in your hosting company's data center(s). The remote server will usually offer some guaranteed level of computing resources (e.g. CPU, RAM, storage memory, etc.) and Internet connectivity for a certain price.

+ +

This sort of remotely accessible computing/networking hardware is referred to as Infrastructure as a Service (IaaS). Many IaaS vendors provide options to preinstall a particular operating system, onto which you must install the other components of your production environment. Other vendors allow you to select more fully-featured environments, perhaps including a complete Django and web-server setup.

+ +
+

Note: Pre-built environments can make setting up your website very easy because they reduce the configuration, but the available options may limit you to an unfamiliar server (or other components) and may be based on an older version of the OS. Often it is better to install components yourself, so that you get the ones that you want, and when you need to upgrade parts of the system, you have some idea where to start!

+
+ +

Other hosting providers support Django as part of a Platform as a Service (PaaS) offering. In this sort of hosting you don't need to worry about most of your production environment (web server, application server, load balancers) as the host platform takes care of those for you (along with most of what you need to do in order to scale your application). That makes deployment quite easy, because you just need to concentrate on your web application and not all the other server infrastructure.

+ +

Some developers will choose the increased flexibility provided by IaaS over PaaS, while others will appreciate the reduced maintenance overhead and easier scaling of PaaS. When you're getting started, setting up your website on a PaaS system is much easier, and so that is what we'll do in this tutorial.

+ +
+

Tip: If you choose a Python/Django-friendly hosting provider they should provide instructions on how to set up a Django website using different configurations of webserver, application server, reverse proxy, etc (this won't be relevant if you choose a PaaS). For example, there are many step-by-step guides for various configurations in the Digital Ocean Django community docs.

+
+ +

Choosing a hosting provider

+ +

There are well over 100 hosting providers that are known to either actively support or work well with Django (you can find a fairly extensive list at Djangofriendly hosts). These vendors provide different types of environments (IaaS, PaaS), and different levels of computing and network resources at different prices.

+ +

Some of the things to consider when choosing a host:

+ + + +

The good news when you're starting out is that there are quite a few sites that provide "evaluation", "developer", or "hobbyist" computing environments for "free". These are always fairly resource constrained/limited environments, and you do need to be aware that they may expire after some introductory period. They are however great for testing low traffic sites in a real environment, and can provide an easy migration to paying for more resources when your site gets busier. Popular choices in this category include Heroku, Python Anywhere, Amazon Web Services, Microsoft Azure, etc.

+ +

Many providers also have a "basic" tier that provides more useful levels of computing power and fewer limitations. Digital Ocean and Python Anywhere are examples of popular hosting providers that offer a relatively inexpensive basic computing tier (in the $5 to $10USD per month range).

+ +
+

Note: Remember that price is not the only selection criteria. If your website is successful, it may turn out that scalability is the most important consideration.

+
+ +

Getting your website ready to publish

+ +

The Django skeleton website created using the django-admin and manage.py tools are configured to make development easier. Many of the Django project settings (specified in settings.py) should be different for production, either for security or performance reasons.

+ +
+

Tip: It is common to have a separate settings.py file for production, and to import sensitive settings from a separate file or an environment variable. This file should then be protected, even if the rest of the source code is available on a public repository.

+
+ +

The critical settings that you must check are:

+ + + +

Let's change the LocalLibrary application so that we read our SECRET_KEY and DEBUG variables from environment variables if they are defined, but otherwise use the default values in the configuration file.

+ +

Open /locallibrary/settings.py, disable the original SECRET_KEY configuration and add the new lines as shown below in bold. During development no environment variable will be specified for the key, so the default value will be used (it shouldn't matter what key you use here, or if the key "leaks", because you won't use it in production).

+ +
# SECURITY WARNING: keep the secret key used in production secret!
+# SECRET_KEY = 'cg#p$g+j9tax!#a3cup@1$8obt2_+&k3q+pmu)5%asj6yjpkag'
+import os
+SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'cg#p$g+j9tax!#a3cup@1$8obt2_+&k3q+pmu)5%asj6yjpkag')
+
+ +

Then comment out the existing DEBUG setting and add the new line shown below.

+ +
# SECURITY WARNING: don't run with debug turned on in production!
+# DEBUG = True
+DEBUG = bool( os.environ.get('DJANGO_DEBUG', True) )
+
+ +

The value of the DEBUG will be True by default, but will be False if the value of the DJANGO_DEBUG environment variable is set to an empty string, e.g. DJANGO_DEBUG=''.

+ +
+

Note: It would be more intuitive if we could just set and unset the DJANGO_DEBUG environment variable to True and False directly, rather than using "any string" or "empty string" (respectively). Unfortunately environment variable values are stored as Python strings, and the only string that evaluates as False is the empty string (e.g. bool('')==False).

+
+ +

A full checklist of settings you might want to change is provided in Deployment checklist (Django docs). You can also list a number of these using the terminal command below:

+ +
python3 manage.py check --deploy
+
+ +

Example: Installing LocalLibrary on Heroku

+ +

This section provides a practical demonstration of how to install LocalLibrary on the Heroku PaaS cloud.

+ +

Why Heroku?

+ +

Heroku is one of the longest running and popular cloud-based PaaS services. It originally supported only Ruby apps, but now can be used to host apps from many programming environments, including Django!

+ +

We are choosing to use Heroku for several reasons:

+ + + +

While Heroku is perfect for hosting this demonstration it may not be perfect for your real website. Heroku makes things easy to set up and scale, at the cost of being less flexible, and potentially a lot more expensive once you get out of the free tier.

+ +

How does Heroku work?

+ +

Heroku runs Django websites within one or more "Dynos", which are isolated, virtualized Unix containers that provide the environment required to run an application. The dynos are completely isolated and have an ephemeral file system (a short-lived file system that is cleaned/emptied every time the dyno restarts). The only thing that dynos share by default are application configuration variables. Heroku internally uses a load balancer to distribute web traffic to all "web" dynos. Since nothing is shared between them, Heroku can scale an app horizontally simply by adding more dynos (though of course you may also need to scale your database to accept additional connections).

+ +

Because the file system is ephemeral you can't install services required by your application directly (e.g. databases, queues, caching systems, storage, email services, etc). Instead Heroku web applications use backing services provided as independent "add-ons" by Heroku or 3rd parties. Once attached to your web application, the dynos access the services using information contained in application configuration variables.

+ +

In order to execute your application Heroku needs to be able to set up the appropriate environment and dependencies, and also understand how it is launched. For Django apps we provide this information in a number of text files:

+ + + +

Developers interact with Heroku using a special client app/terminal, which is much like a Unix bash script. This allows you to upload code that is stored in a git repository, inspect the running processes, see logs, set configuration variables and much more!

+ +

In order to get our application to work on Heroku we'll need to put our Django web application into a git repository, add the files above, integrate with a database add-on, and make changes to properly handle static files.

+ +

Once we've done all that we can set up a Heroku account, get the Heroku client, and use it to install our website.

+ +
+

Note: The instructions below reflect how to work with Heroku at time of writing. If Heroku significantly change their processes, you may wish to instead check their setup documents: Getting Started on Heroku with Django.

+
+ +

That's all the overview you need in order to get started (see How Heroku works for a more comprehensive guide).

+ +

Creating an application repository in Github

+ +

Heroku is closely integrated with the git source code version control system, using it to upload/synchronise any changes you make to the live system. It does this by adding a new heroku "remote" repository named heroku pointing to a repository for your source on the Heroku cloud. During development you use git to store changes on your "master" repository. When you want to deploy your site, you sync your changes to the Heroku repository.

+ +
+

Note: If you're used to following good software development practices you are probably already using git or some other SCM system. If you already have a git repository, then you can skip this step.

+
+ +

There are a lot of ways of to work with git, but one of the easiest is to first set up an account on Github, create the repository there, and then sync to it locally:

+ +
    +
  1. Visit https://github.com/ and create an account.
  2. +
  3. Once you are logged in, click the + link in the top toolbar and select New repository.
  4. +
  5. Fill in all the fields on this form. While these are not compulsory, they are strongly recommended. +
      +
    • Enter a new repository name (e.g. django_local_library), and description (e.g. "Local Library website written in Django".
    • +
    • Choose Python in the Add .gitignore selection list.
    • +
    • Choose your preferred license in the Add license selection list.
    • +
    • Check Initialize this repository with a README.
    • +
    +
  6. +
  7. Press Create repository.
  8. +
  9. Click the green "Clone or download" button on your new repo page.
  10. +
  11. Copy the URL value from the text field inside the dialog box that appears (it should be something like: https://github.com/<your_git_user_id>/django_local_library.git).
  12. +
+ +

Now the repository ("repo") is created we are going to want to clone it on our local computer:

+ +
    +
  1. Install git for your local computer (you can find versions for different platforms here).
  2. +
  3. Open a command prompt/terminal and clone your repository using the URL you copied above: +
    git clone https://github.com/<your_git_user_id>/django_local_library.git
    +
    + This will create the repository below the current point.
  4. +
  5. Navigate into the new repo. +
    cd django_local_library.git
    +
  6. +
+ +

The final step is to copy in your application and then add the files to your repo using git:

+ +
    +
  1. Copy your Django application into this folder (all the files at the same level as manage.py and below, not their containing locallibrary folder).
  2. +
  3. Open the .gitignore file, copy the following lines into the bottom of it, and then save (this file is used to identify files that should not be uploaded to git by default). +
    # Text backup files
    +*.bak
    +
    +#Database
    +*.sqlite3
    +
  4. +
  5. Open a command prompt/terminal and use the add command to add all files to git. +
    git add -A
    +
    +
  6. +
  7. Use the status command to check all files that you are about to add are correct (you want to include source files, not binaries, temporary files etc.). It should look a bit like the listing below. +
    > git status
    +On branch master
    +Your branch is up-to-date with 'origin/master'.
    +Changes to be committed:
    +  (use "git reset HEAD <file>..." to unstage)
    +
    +        modified:   .gitignore
    +        new file:   catalog/__init__.py
    +        ...
    +        new file:   catalog/migrations/0001_initial.py
    +        ...
    +        new file:   templates/registration/password_reset_form.html
    +
  8. +
  9. When you're satisfied commit the files to your local repository: +
    git commit -m "First version of application moved into github"
    +
  10. +
  11. Then synchronise your local repository to the Github website, using the following: +
    git push origin master
    +
  12. +
+ +

When this operation completes, you should be able to go back to the page on Github where you created your repo, refresh the page, and see that your whole application has now been uploaded. You can continue to update your repository as files change using this add/commit/push cycle.

+ +
+

Tip: This is a good point to make a backup of your "vanilla" project — while some of the changes we're going to be making in the following sections might be useful for deployment on any platform (or development) others might not.

+ +

The best way to do this is to use git to manage your revisions. With git you can not only go back to a particular old version, but you can maintain this in a separate "branch" from your production changes and cherry-pick any changes to move between production and development branches. Learning Git is well worth the effort, but is beyond the scope of this topic.

+ +

The easiest way to do this is to just copy your files into another location. Use whichever approach best matches your knowledge of git!

+
+ +

Update the app for Heroku

+ +

This section explains the changes you'll need to make to our LocalLibrary application to get it to work on Heroku. While Heroku's Getting Started on Heroku with Django instructions assume you will use the Heroku client to also run your local development environment, our changes here are compatible with the existing Django development server and ways of working we've already learned.

+ +

Procfile

+ +

Create the file Procfile (no extension) in the root of your GitHub repository to declare the application's process types and entry points. Copy the following text into it:

+ +
web: gunicorn locallibrary.wsgi --log-file -
+ +

The "web:" tells Heroku that this is a web dyno and can be sent HTTP traffic. The process to start in this dyno is gunicorn, which is a popular web application server that Heroku recommends. We start Gunicorn using the configuration information in the module locallibrary.wsgi (created with our application skeleton: /locallibrary/wsgi.py).

+ +

Gunicorn

+ +

Gunicorn is the recommended HTTP server for use with Django on Heroku (as referenced in the Procfile above). It is a pure-Python HTTP server for WSGI applications that can run multiple Python concurrent processes within a single dyno (see Deploying Python applications with Gunicorn for more information).

+ +

While we won't need Gunicorn to serve our LocalLibrary application during development, we'll install it so that it becomes part of our requirements for Heroku to set up on the remote server.

+ +

Install Gunicorn locally on the command line using pip (which we installed when setting up the development environment):

+ +
pip3 install gunicorn
+
+ +

Database configuration

+ +

We can't use the default SQLite database on Heroku because it is file-based, and it would be deleted from the ephemeral file system every time the application restarts (typically once a day, and every time the application or its configuration variables are changed).

+ +

The Heroku mechanism for handling this situation is to use a database add-on and configure the web application using information from an environment configuration variable, set by the add-on. There are quite a lot of database options, but we'll use the hobby tier of the Heroku postgres database as this is free, supported by Django, and automatically added to our new Heroku apps when using the free hobby dyno plan tier.

+ +

The database connection information is supplied to the web dyno using a configuration variable named DATABASE_URL. Rather than hard-coding this information into Django, Heroku recommends that developers use the dj-database-url package to parse the DATABASE_URL environment variable and automatically convert it to Django’s desired configuration format. In addition to installing the dj-database-url package we'll also need to install psycopg2, as Django needs this to interact with Postgres databases.

+ +
dj-database-url (Django database configuration from environment variable)
+ +

Install dj-database-url locally so that it becomes part of our requirements for Heroku to set up on the remote server:

+ +
$ pip3 install dj-database-url
+
+ +
settings.py
+ +

Open /locallibrary/settings.py and copy the following configuration into the bottom of the file:

+ +
# Heroku: Update database configuration from $DATABASE_URL.
+import dj_database_url
+db_from_env = dj_database_url.config(conn_max_age=500)
+DATABASES['default'].update(db_from_env)
+ +
+

Note:

+ + +
+ +
psycopg2 (Python Postgres database support)
+ +

Django needs psycopg2 to work with Postgres databases and you will need to add this to the requirements.txt for Heroku to set this up on the remote server (as discussed in the requirements section below).

+ +

Django will use our SQLite database locally by default, because the DATABASE_URL environment variable isn't set in our local environment. If you want to switch to Postgres completely and use our Heroku free tier database for both development and production then you can. For example, to install psycopg2 and its dependencies locally on a Linux-based system you would use the following bash/terminal commands:

+ +
sudo apt-get install python-pip python-dev libpq-dev postgresql postgresql-contrib
+pip3 install psycopg2
+
+ +

Installation instructions for the other platforms can be found on the psycopg2 website here.

+ +

However, you don't need to do this — you don't need PostGreSQL active on the local computer, as long as you give it to Heroku as a requirement, in requirements.txt (see below).

+ +

Serving static files in production

+ +

During development we used Django and the Django development web server to serve our static files (CSS, JavaScript, etc.). In a production environment we instead typically serve static files from a content delivery network (CDN) or the web server.

+ +
+

Note: Serving static files via Django/web application is inefficient because the requests have to pass through unnecessary additional code (Django) rather than being handled directly by the web server or a completely separate CDN. While this doesn't matter for local use during development, it would have a significant performance impact if we were to use the same approach in production. 

+
+ +

To make it easy to host static files separately from the Django web application, Django provides the collectstatic tool to collect these files for deployment (there is a settings variable that defines where the files should be collected when collectstatic is run). Django templates refer to the hosting location of the static files relative to a settings variable (STATIC_URL), so that this can be changed if the static files are moved to another host/server.

+ +

The relevant setting variables are:

+ + + +
settings.py
+ +

Open /locallibrary/settings.py and copy the following configuration into the bottom of the file. The BASE_DIR should already have been defined in your file (the STATIC_URL may already have been defined within the file when it was created. While it will cause no harm, you might as well delete the duplicate previous reference).

+ +
# Static files (CSS, JavaScript, Images)
+# https://docs.djangoproject.com/en/2.0/howto/static-files/
+
+# The absolute path to the directory where collectstatic will collect static files for deployment.
+STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
+
+# The URL to use when referring to static files (where they will be served from)
+STATIC_URL = '/static/'
+
+ +

We'll actually do the file serving using a library called WhiteNoise, which we install and configure in the next section.

+ +

For more information, see Django and Static Assets (Heroku docs).

+ +

Whitenoise

+ +

There are many ways to serve static files in production (we saw the relevant Django settings in the previous sections). Heroku recommends using the WhiteNoise project for serving of static assets directly from Gunicorn in production.

+ +
+

Note: Heroku automatically calls collectstatic and prepares your static files for use by WhiteNoise after it uploads your application. Check out WhiteNoise documentation for an explanation of how it works and why the implementation is a relatively efficient method for serving these files.

+
+ +

The steps to set up WhiteNoise to use with the project are:

+ +
WhiteNoise
+ +

Install whitenoise locally using the following command:

+ +
$ pip3 install whitenoise
+
+ +
settings.py
+ +

To install WhiteNoise into your Django application, open /locallibrary/settings.py, find the MIDDLEWARE setting and add the WhiteNoiseMiddleware near the top of the list, just below the SecurityMiddleware:

+ +
MIDDLEWARE = [
+    'django.middleware.security.SecurityMiddleware',
+    'whitenoise.middleware.WhiteNoiseMiddleware',
+    'django.contrib.sessions.middleware.SessionMiddleware',
+    'django.middleware.common.CommonMiddleware',
+    'django.middleware.csrf.CsrfViewMiddleware',
+    'django.contrib.auth.middleware.AuthenticationMiddleware',
+    'django.contrib.messages.middleware.MessageMiddleware',
+    'django.middleware.clickjacking.XFrameOptionsMiddleware',
+]
+
+ +

Optionally, you can reduce the size of the static files when they are served (this is more efficient). Just add the following to the bottom of /locallibrary/settings.py:

+ +
# Simplified static file serving.
+# https://warehouse.python.org/project/whitenoise/
+STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
+
+ +

Requirements

+ +

The Python requirements of your web application must be stored in a file requirements.txt in the root of your repository. Heroku will then install these automatically when it rebuilds your environment. You can create this file using pip on the command line (run the following in the repo root):

+ +
pip3 freeze > requirements.txt
+ +

After installing all the different dependencies above, your requirements.txt file should have at least these items listed (though the version numbers may be different). Please delete any other dependencies not listed below, unless you've explicitly added them for this application.

+ +
dj-database-url==0.4.1
+Django==2.0
+gunicorn==19.6.0
+psycopg2==2.6.2
+whitenoise==3.2.2
+
+ +
+

Make sure that a psycopg2 line like the one above is present! Even iIf you didn't install this locally then you should still add this to the requirements.txt.

+
+ +

Runtime

+ +

The runtime.txt file, if defined, tells Heroku which programming language to use. Create the file in the root of the repo and add the following text:

+ +
python-3.6.4
+ +
+

Note: Heroku only supports a small number of Python runtimes (at time of writing, this includes the one above). Heroku will use a supported runtime irrespective of the value specified in this file.

+
+ +

Save changes to Github and re-test

+ +

Next lets save all our changes to Github. In the terminal (whist inside our repository), enter the following commands:

+ +
git add -A
+git commit -m "Added files and changes required for deployment to heroku"
+git push origin master
+ +

Before we proceed, lets test the site again locally and make sure it wasn't affected by any of our changes above. Run the development web server as usual and then check the site still works as you expect on your browser.

+ +
python3 manage.py runserver
+ +

We should now be ready to start deploying LocalLibrary on Heroku.

+ +

Get a Heroku account

+ +

To start using Heroku you will first need to create an account:

+ + + +

Install the client

+ +

Download and install the Heroku client by following the instructions on Heroku here.

+ +

After the client is installed you will be able run commands. For example to get help on the client:

+ +
heroku help
+
+ +

Create and upload the website

+ +

To create the app we run the "create" command in the root directory of our repository. This creates a git remote ("pointer to a remote repository") named heroku in our local git environment.

+ +
heroku create
+ +
+

Note: You can name the remote if you like by specifying a value after "create". If you don't then you'll get a random name. The name is used in the default URL.

+
+ +

We can then push our app to the Heroku repository as shown below. This will upload the app, package it in a dyno, run collectstatic, and start the site.

+ +
git push heroku master
+ +

If we're lucky, the app is now "running" on the site, but it won't be working properly because we haven't set up the database tables for use by our application. To do this we need to use the heroku run command and start a "one off dyno" to perform a migrate operation. Enter the following command in your terminal:

+ +
heroku run python manage.py migrate
+ +

We're also going to need to be able to add books and authors, so lets also create our administration superuser, again using a one-off dyno:

+ +
heroku run python manage.py createsuperuser
+ +

Once this is complete, we can look at the site. It should work, although it won't have any books in it yet. To open your browser to the new website, use the command:

+ +
heroku open
+ +

Create some books in the admin site, and check out whether the site is behaving as you expect.

+ +

Managing addons

+ +

You can check out the add-ons to your app using the heroku addons command. This will list all addons, and their price tier and state.

+ +
>heroku addons
+
+Add-on                                     Plan       Price  State
+─────────────────────────────────────────  ─────────  ─────  ───────
+heroku-postgresql (postgresql-flat-26536)  hobby-dev  free   created
+ └─ as DATABASE
+ +

Here we see that we have just one add-on, the postgres SQL database. This is free, and was created automatically when we created the app. You can open a web page to examine the database add-on (or any other add-on) in more detail using the following command:

+ +
heroku addons:open heroku-postgresql
+
+ +

Other commands allow you to create, destroy, upgrade and downgrade addons (using a similar syntax to opening). For more information see Managing Add-ons (Heroku docs).

+ +

Setting configuration variables

+ +

You can check out the configuration variables for the site using the heroku config command. Below you can see that we have just one variable, the DATABASE_URL used to configure our database.

+ +
>heroku config
+
+=== locallibrary Config Vars
+DATABASE_URL: postgres://uzfnbcyxidzgrl:j2jkUFDF6OGGqxkgg7Hk3ilbZI@ec2-54-243-201-144.compute-1.amazonaws.com:5432/dbftm4qgh3kda3
+ +

If you recall from the section on getting the website ready to publish, we have to set environment variables for DJANGO_SECRET_KEY and DJANGO_DEBUG. Let's do this now.

+ +
+

Note: The secret key needs to be really secret! One way to generate a new key is to create a new Django project (django-admin startproject someprojectname) and then get the key that is generated for you from its settings.py.

+
+ +

We set DJANGO_SECRET_KEY using the config:set command (as shown below). Remember to use your own secret key!

+ +
>heroku config:set DJANGO_SECRET_KEY=eu09(ilk6@4sfdofb=b_2ht@vad*$ehh9-)3u_83+y%(+phh&=
+
+Setting DJANGO_SECRET_KEY and restarting locallibrary... done, v7
+DJANGO_SECRET_KEY: eu09(ilk6@4sfdofb=b_2ht@vad*$ehh9-)3u_83+y%(+phh
+
+ +

We similarly set DJANGO_DEBUG:

+ +
>heroku config:set DJANGO_DEBUG=
+
+Setting DJANGO_DEBUG and restarting locallibrary... done, v8
+ +

If you visit the site now you'll get a "Bad request" error, because the ALLOWED_HOSTS setting is required if you have DEBUG=False (as a security measure). Open /locallibrary/settings.py and change the ALLOWED_HOSTS setting to include your base app url (e.g. 'locallibrary1234.herokuapp.com') and the URL you normally use on your local development server.

+ +
ALLOWED_HOSTS = ['<your app URL without the https:// prefix>.herokuapp.com','127.0.0.1']
+# For example:
+# ALLOWED_HOSTS = ['fathomless-scrubland-30645.herokuapp.com','127.0.0.1']
+
+ +

Then save your settings and commit them to your Github repo and to Heroku:

+ +
git add -A
+git commit -m 'Update ALLOWED_HOSTS with site and development server URL'
+git push origin master
+git push heroku master
+ +
+

After the site update to Heroku completes, enter an URL that does not exist (e.g. /catalog/doesnotexist/). Previously this would have displayed a detailed debug page, but now you should just see a simple "Not Found" page.

+
+ +

Debugging

+ +

The Heroku client provides a few tools for debugging:

+ +
heroku logs  # Show current logs
+heroku logs --tail # Show current logs and keep updating with any new results
+heroku config:set DEBUG_COLLECTSTATIC=1 # Add additional logging for collectstatic (this tool is run automatically during a build)
+heroku ps   #Display dyno status
+
+ +

If you need more information than these can provide you will need to start looking into Django Logging.

+ + + +

Summary

+ +

That's the end of this tutorial on setting up Django apps in production, and also the series of tutorials on working with Django. We hope you've found them useful. You can check out a fully worked-through version of the source code on Github here.
+
+ The next step is to read our last few articles, and then complete the assessment task.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/Server-side/Django/Testing", "Learn/Server-side/Django/web_application_security", "Learn/Server-side/Django")}}

+ +

 

+ +

In this module

+ + + +

 

diff --git a/files/zh-tw/learn/server-side/django/development_environment/index.html b/files/zh-tw/learn/server-side/django/development_environment/index.html new file mode 100644 index 0000000000..c3d4c5c823 --- /dev/null +++ b/files/zh-tw/learn/server-side/django/development_environment/index.html @@ -0,0 +1,429 @@ +--- +title: 架設 Django 開發環境 +slug: Learn/Server-side/Django/development_environment +translation_of: Learn/Server-side/Django/development_environment +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Django/Introduction", "Learn/Server-side/Django/Tutorial_local_library_website", "Learn/Server-side/Django")}}
+ +

現在,你知道什麼是Django。那麼我們將向你展示如何在Windows,Linux(Ubuntu)和Mac OSX上設置和測試Django開發環境—無論你常用哪種操作系統,本文應該都能讓你開始開發Django應用程序。

+ + + + + + + + + + + + +
先備知識:知道如何打開終端或命令行。了解如何在計算機的操作系統上安裝軟件包。
目標:在你的計算機操作系統上運行Django(2.0)開發環境。
+ +

Django 開發環境概覽

+ +

Django 使你輕鬆設置自己的電腦,以便開始開發網絡應用。這部分介紹在開發環境可以取得什麼,並概述了部分設置和配置選項。本文的其餘部分,介紹了在Ubuntu,Mac OS X 和 Windows 上,安裝 Django 開發環境的推薦方法,以及如何測試。

+ +

什麼是 Django 開發環境?

+ +

開發環境是在本地計算機上安裝 Django,你可以在將 Django 部署到生產環境之前,用於開發和測試 Django 應用程序。

+ +

Django 本身提供的主要工具,是一組用於創建和使用 Django 項目的 Python 腳本,以及可用於在你的計算機的瀏覽器上,測試本地(即,你的計算機,而不是外部 Web 服務器)Django 網絡應用程序的簡單開發網路服務器 。

+ +

還有其他外部工具, 它們構成了開發環境的一部分, 我們將不再贅述。這些包括 文本編輯器 text editor 或編輯代碼的 IDE,以及像 Git 這樣的源代碼控制管理工具,用於安全地管理不同版本的代碼。我們假設你已經安裝了一個文本編輯器。

+ +

什麼是Django設置選項?

+ +

Django 如何在安裝和配置方面非常靈活。Django可以:

+ + + +

每個選項都需要略微不同的配置和設置。以下小節解釋了你的一些選擇。對於本文的其餘部分,我們將介紹Django在少見的操作系統上的設置,考量該模塊的其餘部分。

+ +
+

注意: 其他可能的安裝選項在官方Django文檔中介紹。相應文件點擊這裡

+
+ +

支持哪些操作系統?

+ +

幾乎任何可以運行Python編程語言的機器可以運行Django 網絡應用程序:Windows,Mac OSX,Linux/Unix,Solaris,僅舉幾例。幾乎任何計算機都應該在開發過程中運行Django所需的性能。

+ +

在本文中。我們將提供Windows,Mac OS X 和Linux/Unix的說明。

+ +

你應該使用什麼版本的Python?

+ +

我們建議您使用最新版本 - 在編寫本文時,這是Python 3.7。

+ +

如果需要,可以使用Python 3.4或更高版本(將來的版本中將刪除Python 3.4支持)。

+ +
+

注意: Python 2.7不能與Django 2.0一起使用(Django 1.11.x系列是最後一個支持Python 2.7的系列)。

+
+ +

我們在哪裡下載Django?

+ +

有三個地方可以下載Django:

+ + + +

本文介紹如何從PyPi安裝Django,從獲得最新的穩定版本。

+ +

哪個數據庫?

+ +

Django支持四個主要數據庫(PostgreSQL,MySQL,Oracle和SQLite),還有一些社區庫,可以為其他流行的SQL和NOSQL數據庫,提供不同級別的支持。我們建議你為生產和開發,選擇相同的數據庫(儘管Django使用其對象關係映射器(ORM)抽像出許多數據庫差異,但是仍然存在可以避免的潛在問題 ).

+ +

對於本文(和本模塊的大部分),我們將使用將數據存放在文件中的SQLite數據庫。SQLite旨在用作輕量級數據庫,不能支持高級並發。然而,這確實是唯讀的應用程序的絕佳選擇。

+ +
+

注意 :當你使用標準工具(django-admin)啟動你的網站項目時,Django將默認配置為使用SQLite。用來入門,這是一個很好的選擇,因為它不需要額外的配置和設置。

+
+ +

安裝到整個本機系統還是Python虛擬環境中?

+ +

安裝Python3時,您將獲得一個由所有Python3代碼共享的單一全局環境。雖然您可以在環境中,安裝任何您喜歡的Python軟件包,但您一次只能安裝每個軟件包的一個特定版本。

+ +
+

注意: 安裝到全局環境中的Python應用程序可能會相互衝突(即,如果它們依賴於同一程序包的不同版本)。

+
+ +

如果您將Django安裝到默認/全局環境中,那麼您將只能在計算機上,定位一個版本的Django。如果您想要創建新網站(使用最新版本的Django)同時仍然維護依賴舊版本的網站,這可能是一個問題。

+ +

因此,經驗豐富的Python / Django開發人員,通常在獨立的Python虛擬環境中,運行Python應用程序。這樣可以在一台計算機上,實現多個不同的Django環境。 Django開發團隊本身建議您使用Python虛擬環境!

+ +

本模塊假設您已將Django安裝到虛擬環境中,我們將向您展示如何做。

+ +

安裝 Python 3

+ +

為了使用Django,你需要安裝Python3.同樣你需要Python包管理工具   — pip3 —用來管理(安裝,更新和刪除)Django和其他Python應用程序使用的Python軟件包/庫。

+ +

本書簡要說明如何根據需要檢查什麼版本,並根據需要安裝新版本,適用於Ubuntu Linux 16.04, Mac OS X, and Windows 10。

+ +
+

注意 :根據你的平台,您還可以從操作系統自己的軟件包管理器或其他機制安裝Python / pip。對於大多數平台,您可以從https://www.python.org/downloads/下載所需的安裝文件,並使用適當的平台特定方法進行安裝。

+
+ +

Ubuntu 18.04

+ +

Ubuntu Linux 18.04 LTS默認包含Python 3.6.5。您可以通過在bash終端中運行以下命令來確認:

+ +
python3 -V
+ Python 3.6.5
+ +

然而,在默認情況下,為Python 3(包括Django)安裝軟件包的Python包管理工具不可用。可以使用以下方式將pip3安裝在bash終端

+ +
sudo apt install python3-pip
+
+ +

macOS X

+ +

Mac OS X "El Capitan" 不包括Python 3.你可以通過在bash終端中運行一下命令來確認:

+ +
python3 -V
+ -bash: python3: command not found
+ +

你可以輕鬆從python.org安裝Python 3(以及pip3工具):

+ +
    +
  1. 下載所需的安裝程序: + +
      +
    1. 點擊https://www.python.org/downloads/
    2. +
    3. 選擇Download Python 3.7.0按鈕(確切的版本號可能不同).
    4. +
    +
  2. +
  3. 使用Finder找到文件,然後雙擊包文件。遵循安裝提示。
    + (一般能拖拽就拖拽)
  4. +
+ +

你現在可以檢查Pyhon 3來確認成功安裝,如下所示:

+ +
python3 -V
+ Python 3.7.0
+
+ +

你也可以通過列出可用的軟件包來檢查pip3是否安裝:

+ +
pip3 list
+ +

Windows 10

+ +

windows默認不安裝,但你可以從python.org輕鬆安裝它(以及pip3工具):

+ +
    +
  1. 下載所需版本: + +
      +
    1. 點擊https://www.python.org/downloads/
    2. +
    3. 選擇Download Python 3.7.0 按鈕(確切的版本號可能不同).
    4. +
    5. 通過雙擊下載的文件並按照提示安裝Python
    6. +
    +
  2. +
+ +

你可以通過在命令提示符中輸入以下文本來驗證是否安裝了Python:

+ +
py -3 -V
+ Python 3.7.0
+
+ +

默認情況下,Windows安裝程序包含pip3(python包管理器,你可以列出安裝的軟件包):

+ +
pip3 list
+
+ +
+

注意: 安裝程序應設置上述命令工作所需的一切。但是,如果您收到無法找到Python 的消息,則可能忘記將其添加到系統路徑中。您可以通過再次運行安裝程序,選擇“修改”"Modify",然後選中第二頁上標有“將Python添加到環境變量”"Add Python to environment variables"的框來執行此操作。

+
+ +

在Python虛擬環境中使​​用Django

+ +

我們將用於創建虛擬環境的庫是 virtualenvwrapper(Linux和macOS X)和 virtualenvwrapper-win (Windows),後者又使用 virtualenv工具。包裝工具為所有平台上的接口管理創建了一致的界面。

+ +

安裝虛擬環境軟體

+ +

Ubuntu虛擬環境設置

+ +

安裝Python和pip之後,你可以安裝 virtualenvwrapper(包括virtualenv)。可在此處找到官方安裝指南,或按照以下說明操作。

+ +

使用pip3安裝該工具:

+ +
sudo pip3 install virtualenvwrapper
+ +

然後將以下行添加到shell啟動文件的末尾(這是主目錄中的隱藏文件名.bashrc)。這些設置了虛擬環境應該存在的位置,開發項目目錄的位置以及使用此軟件包安裝的腳本的位置 :

+ +
export WORKON_HOME=$HOME/.virtualenvs
+export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
+export VIRTUALENVWRAPPER_VIRTUALENV_ARGS=' -p /usr/bin/python3 '
+export PROJECT_HOME=$HOME/Devel
+source /usr/local/bin/virtualenvwrapper.sh
+
+ +
+

注意: VIRTUALENVWRAPPER_PYTHONVIRTUALENVWRAPPER_VIRTUALENV_ARGS 變量指向Python3的正常安裝位置,source /usr/local/bin/virtualenvwrapper.sh指向virtualenvwrapper.sh腳本的正常位置。如果virtualenv在測試時不起作用,那麼要檢查的一件事是Python和腳本位於預期的位置(然後適當地更改啟動文件)。

+ +

您可以使用which virtualenvwrapper.shwhich python3.的命令找到系統的正確位置。

+
+ +

然後在終端中運行以下命令重新加載啟動文件:

+ +
source ~/.bashrc
+ +

此時您應該看到一堆腳本正在運行,如下所示:

+ +
virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/premkproject
+virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/postmkproject
+...
+virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/preactivate
+virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/postactivate
+virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/get_env_details
+
+ +

現在,您可以使用mkvirtualenv命令創建新的虛擬環境。

+ +

macOS X 虛擬環境設置

+ +

在 macOS X上設置 virtualenvwrapper 與在 Ubuntu上幾乎完全相同(同樣,您可以按照官方安裝指南或下面的說明進行操作。

+ +

使用 pip 安裝 virtualenvwrapper(並捆綁 virtualenv),如圖所示。

+ +
sudo pip3 install virtualenvwrapper
+ +

然後將以下幾行添加到 shell 啟動文件的末尾。

+ +
export WORKON_HOME=$HOME/.virtualenvs
+export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
+export PROJECT_HOME=$HOME/Devel
+source /usr/local/bin/virtualenvwrapper.sh
+ +
+

注意: VIRTUALENVWRAPPER_PYTHON變量指向Python3的正常安裝位置,source /usr/local/bin/virtualenvwrapper.sh指向virtualenvwrapper.sh腳本的正常位置。如果virtualenv在測試時不起作用,那麼要檢查的一件事,是Python和腳本位於預期的位置(然後適當地更改啟動文件)。

+ +

例如,對macOS進行的一次安裝測試,最終在啟動文件中需要以下幾行:

+ +
export WORKON_HOME=$HOME/.virtualenvs
+export VIRTUALENVWRAPPER_PYTHON=/Library/Frameworks/Python.framework/Versions/3.7/bin/python3
+export PROJECT_HOME=$HOME/Devel
+source /Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenvwrapper.sh
+ +

您可以使用which virtualenvwrapper.shwhich python3的命令找到系統的正確位置。

+
+ +

這幾行與Ubuntu相同,但啟動文件是主目錄中、名稱不同的隱藏文件.bash_profile

+ +
+

注意: 如果在查找程序中找不到要編輯的.bash-profile,也可以使用nano在終端中打開它。

+ +

命令看起來像這樣:

+ +
cd ~  # Navigate to my home directory
+ls -la #List the content of the directory. YOu should see .bash_profile
+nano .bash_profile # Open the file in the nano text editor, within the terminal
+# Scroll to the end of the file, and copy in the lines above
+# Use Ctrl+X to exit nano, Choose Y to save the file.
+
+ +

 

+
+ +

然後通過在終端中,進行以下調用,來重新加載啟動文件:

+ +
source ~/.bash_profile
+ +

此時,您可能會看到一堆腳本正在運行(與Ubuntu安裝相同的腳本)。您現在應該能夠使用mkvirtualenv命令,創建新的虛擬環境。

+ +

Windows 10 虛擬環境設置

+ +

安裝virtualenvwrapper-win比設置virtualenvwrapper更簡單,因為您不需要配置工具存放虛擬環境信息的位置(有默認值)。您需要做的就是,在命令提示符中運行以下命令:

+ +
pip3 install virtualenvwrapper-win
+ +

現在,您可以使用mkvirtualenv命令創建新的虛擬環境

+ +

創建虛擬環境

+ +

一旦你安裝了virtualenvwrapper或virtualenvwrapper-win,那麼在所有平台上使用虛擬環境都非常相似。

+ +

現在,您可以使用mkvirtualenv命令創建新的虛擬環境。當此命令運行時,您將看到正在設置的環境(您看到的是略微特定​​於平台的)。當命令完成時,新的虛擬環境,將處於活動狀態 - 您可以看到這一點,因為提示的開頭,將是括號中環境的名稱(如下所示)。

+ +
$ mkvirtualenv my_django_environment
+
+Running virtualenv with interpreter /usr/bin/python3
+...
+virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/t_env7/bin/get_env_details
+(my_django_environment) ubuntu@ubuntu:~$
+
+ +

現在,您可以在虛擬環境中,安裝Django,並開始開發。

+ +
+

注意: 從本文開始(實際上是本系列教學),請假設任何命令都在Python虛擬環境中運行,就像我們在上面設置的那樣。

+
+ +

使用虛擬環境

+ +

您應該知道其他一些有用的命令(工具文檔中有更多,但這些是您經常使用的命令):

+ + + +

安裝 Django

+ +

一旦你創建了一個虛擬環境,並調用了workon來輸入它,就可以使用pip3來安裝Django。

+ +
pip3 install django
+
+ +

您可以通過運行以下命令來測試Django是否安裝(這只是測試Python可以找到Django模塊):

+ +
# Linux/macOS X
+python3 -m django --version
+ 2.0
+
+# Windows
+py -3 -m django --version
+ 2.0
+
+ +
+

注意: 如果上面的Windows命令沒有顯示django模塊,請嘗試:

+ +
py -m django --version
+在Windows中,Python 3腳本通過在命令前面加上py -3來啟動,儘管這可能會因具體安裝而異。如果遇到任何命令問題,請嘗試省略-3修飾符。在Linux / macOS X中,命令是python3
+ +
+

重要提示:本教程的其餘部分,使用Linux命令來調用Python 3(python3)。如果您在Windows上工作,只需將此前綴替換為: py -3

+
+ +

測試你的安裝

+ +

上面的測試可以工作,但它不是很有趣。一個更有趣的測試是創建一個骨架項目並看到它工作。要做到這一點,先在你的命令提示符/終端導航到你想存儲你Django應用程序的位置。為您的測試站點創建一個文件夾並瀏覽它。

+ +
mkdir django_test
+cd django_test
+
+ +

然後,您可以使用django-admin工具創建一個名為“ mytestsite ”的新骨架站點,如圖所示。創建網站後,您可以導航到文件夾,您將在其中找到管理項目的主要腳本,名為manage.py

+ +
django-admin startproject mytestsite
+cd mytestsite
+ +

我們可以使用manage.pyrunserver 命令,從此文件夾內運行開發Web服務器,如圖所示。

+ +
$ python3 manage.py runserver
+Performing system checks...
+
+System check identified no issues (0 silenced).
+
+You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
+Run 'python manage.py migrate' to apply them.
+
+December 29, 2017 - 03:03:47
+Django version 2.0, using settings 'mytestsite.settings'
+Starting development server at http://127.0.0.1:8000/
+Quit the server with CONTROL-C.
+
+ +
+

注意: 以上命令顯示Linux / macOS X命令。此時您可以忽略有關“14個未應用的遷移”的警告!("14 unapplied migration(s)" )

+
+ +

一旦服務器運行,您可以通過導航到本地Web瀏覽器上的以下URL來查看該站點:http://127.0.0.1:8000/你應該看到一個如下所示的網站:

+ +

Django Skeleton App Homepage

+ + + +

總結Summary

+ +

您現在已在計算機上啟動並運行Django開發環境。

+ +

在測試部分,您還簡要了解了,我們如何使用django-admin startproject,創建一個新的Django網站,並使用開發Web服務器(python3 manage.py runserver)在瀏覽器中運行它。在下一篇文章中,我們將擴展此過程,構建一個簡單、但完整的Web應用程序。

+ +

參閱

+ + + +

{{PreviousMenuNext("Learn/Server-side/Django/Introduction", "Learn/Server-side/Django/Tutorial_local_library_website", "Learn/Server-side/Django")}}

+ +

本教程連結

+ + + +

 

diff --git a/files/zh-tw/learn/server-side/django/django_assessment_blog/index.html b/files/zh-tw/learn/server-side/django/django_assessment_blog/index.html new file mode 100644 index 0000000000..d584b8259c --- /dev/null +++ b/files/zh-tw/learn/server-side/django/django_assessment_blog/index.html @@ -0,0 +1,316 @@ +--- +title: 'Assessment: DIY Django mini blog' +slug: Learn/Server-side/Django/django_assessment_blog +tags: + - django + - 初學者 + - 部落格 +translation_of: Learn/Server-side/Django/django_assessment_blog +--- +
{{LearnSidebar}}
+ +
{{PreviousMenu("Learn/Server-side/Django/web_application_security", "Learn/Server-side/Django")}}
+ +

在這個評估中,您將使用您在 Django Web Framework (Python) 模組中獲得的知識,來創建一個非常基本的部落格。

+ + + + + + + + + + + + +
+

前提:

+
在開始時做這章節的任務之前,你應該已經看完這個模組的所有文章了。
目標: +

測試Django基礎的綜合應用,包含URL設定、模型、視圖、表單和模板。

+
+ +

專案簡介

+ +

需要顯示的頁面與對應的URLs和需求提列於下表:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
頁面URL需求
首頁/ 和 /blog/關於此站的說明。
所有部落格文章的清單/blog/blogs/ +

所有部落格文章的清單。

+ +
    +
  • 所有使用者都能從側邊選單進入此頁。
  • +
  • 清單按發布日期排序(新至舊)。
  • +
  • 清單依照每頁5筆文章分頁。
  • +
  • 清單內的每一筆項目顯示文章標題、發布日期與作者的名字。
  • +
  • 文章標題連結至該至文章的詳細頁面。
  • +
  • 作者的名字連結至該作者的詳細頁面。
  • +
+
部落格作者(blogger) 詳細頁面/blog/blogger/<author-id> +

特定作者(由id指定)的資訊與他所發布的部落格文章。

+ +
    +
  • 所有使用者都能從作者連結進入此頁(例如文章內的作者連結)。
  • +
  • 包含一些關於作者本身的資訊。
  • +
  • 文章清單按發布日期排序(新至舊)。
  • +
  • 不用分頁。
  • +
  • 文章清單只顯示文章標題與發佈日期。
  • +
  • 文章標題連結至文章詳細頁面。
  • +
+
部落格文章詳細頁面/blog/<blog-id> +

部落格文章詳細內容。

+ +
    +
  • 任何使用者都能從部落格文章的清單進入此頁。
  • +
  • 包含文章標題、作者、發布日期與內容。
  • +
  • 文章的回覆必須呈現於底部。
  • +
  • 文章的回覆必須按回覆時間排序(舊至新)。
  • +
  • 已登入的使用者能看見新增回覆的連結。
  • +
  • 文章與回覆需以純文字的方式顯示。不需要支援任何markup(例如連結、圖片、粗體/斜體等)。
  • +
+
部落格作者清單/blog/bloggers/ +

系統內的部落格作者清單。

+ +
    +
  • 任何使用者都可以從側邊選單進入此頁。
  • +
  • 作者名字連結至該作者的詳細頁面。
  • +
+
回覆表單頁/blog/<blog-id>/create +

新增回覆於特定文章。

+ +
    +
  • 只有登入的使用者可以由文章詳細頁面底部連結進入此頁。
  • +
  • 提供能輸入回覆的表單(發布日期和文章標題不可被編輯)。
  • +
  • 回覆被發表之後,頁面會轉址回該文章詳細頁。
  • +
  • 使用者無法修改或是刪除他發表的回覆。
  • +
  • 未登入的使用者會先被導至登入頁,登入之後才能發表回覆。一旦登入之後,他們便會被導至他們想發表回覆的文章頁。
  • +
  • 回覆表單頁必須包含該文章的標題與連結。
  • +
+
使用者身分認證頁/accounts/<standard urls> +

標準的Django身分驗證頁面,用來登入、登出及修改密碼。

+ +
    +
  • 使用者能從側欄連結進入登入/登出頁面。
  • +
+
管理者網頁/admin/<standard urls> +

管理者網頁必須能新增/編輯/刪除部落格文章、作者及回覆。

+ +
    +
  • 管理者網頁的每筆文章記錄必須一併於其底下陳列出相關的回覆。
  • +
  • 管理者網頁的每一筆回覆都要以75字的回覆內容作為顯示名稱。
  • +
  • 其餘的紀錄使用基本的註冊即可。
  • +
+
+ +

另外您應該要寫一些基本的測試來驗證:

+ + + +
+

Note: 當然你也可以跑很多其他的測試。但是我們會希望您至少實作以上列出的測試項目。

+
+ +

下一區塊顯示符合以上需求的網頁截圖

+ +

截圖

+ +

The following screenshot provide an example of what the finished program should output.

+ +

列出所有的部落格文章

+ +

這個頁面會列出所有部落格內的文章(可以從側邊選單的“所有文章”連結進入)。
+ 幾項提醒:

+ + + +

List of all blogs

+ +

列出所有部落客(文章作者)

+ +

可以由側邊選單的“所有部落客”進入此頁面,並於頁面上提供連結至每一位部落客。
+ 從截圖可以發現到,並沒有任何一位使用者登入。

+ +

List of all bloggers

+ +

部落格詳細頁

+ +

顯示某篇特定部落格文章的詳細內容。

+ +

Blog detail with add comment link

+ +

請注意每個評論都有日期與時間,並且由最後至最新排列(與部落格文章相反)。
+ 我們可以看見最底下有個連結連到新增評論的表單。當使用者沒有登入時,我們改以要求登入的連結代替。

+ +

Comment link when not logged in

+ +

新增評論表單

+ +

這張表單用來新增評論,且使用者必須是登入狀態。當表單送出成功之後,我們必須回到相對應的部落格文章內容頁。

+ +

Add comment form

+ +

作者資料

+ +

這頁顯示部落客的介紹資料以及列出他們所發表的部落格文章。

+ +

Blogger detail page

+ +

一步一腳印Steps to complete

+ +

以下說明實作的步驟。

+ +
    +
  1. 建立一個此網站的專案及app骨架(可以參考Django 教學2 : 建立一個網站骨架)。你也許會用'diyblog'作為專案名稱,‘blog'作為app的名稱。
  2. +
  3. 建立部落格文章、評論與其他任何所需物件的模型。當你在思考怎麼設計的時候,請記得: +
      +
    • 每一個評論都只屬於一篇部落格文章,但每一個部落格文章可以有很多筆評論。
    • +
    • 部落格文章必須要依照發布時間排序(新至舊),評論要依照發布排序(舊至新)。
    • +
    • 不是每位使用者都是部落客,但是每一位使用者都可以留下評論。
    • +
    • 部落客必須有介紹資訊。
    • +
    +
  4. +
  5. 跑migrations以及創建一個新的超級使用者(superuser)。
  6. +
  7. 透過admin網站新稱一些部落格文章和評論。
  8. +
  9. 幫部落格文章列表頁與部落客列表頁建立視圖、模板及設定URL。
  10. +
  11. 幫部落格文章詳細頁與部落客詳細頁建立視圖、模板及設定URL。
  12. +
  13. 建立一個頁面包含可以新增評論的表單(記得只有已登入的使用者可以進入此頁!)
  14. +
+ +

提示與小技巧

+ +

This project is very similar to the LocalLibrary tutorial. You will be able to set up the skeleton, user login/logout behaviour, support for static files, views, URLs, forms, base templates and admin site configuration using almost all the same approaches.

+ +

Some general hints:

+ +
    +
  1. The index page can be implemented as a basic function view and template (just like for the locallibrary).
  2. +
  3. The list view for blog posts and bloggers, and the detail view for blog posts can be created using the generic list and detail views.
  4. +
  5. The list of blog posts for a particular author can be created by using a generic list Blog list view and filtering for blog object that match the specified author. +
      +
    • You will have to implement get_queryset(self) to do the filtering (much like in our library class LoanedBooksAllListView) and get the author information from the URL.
    • +
    • You will also need to pass the name of the author to the page in the context. To do this in a class-based view you need to implement get_context_data() (discussed below).
    • +
    +
  6. +
  7. The add comment form can be created using a function-based view (and associated model and form) or using a generic CreateView. If you use a CreateView (recommended) then: +
      +
    • You will also need to pass the name of the blog post to the comment page in the context (implement get_context_data() as discussed below).
    • +
    • The form should only display the comment "description" for user entry (date and associated blog post should not be editable). Since they won't be in the form itself, your code will need to set the comment's author in the form_valid() function so it can be saved into the model (as described here — Django docs). In that same function we set the associated blog. A possible implementation is shown below (pk is a blog id passed in from the URL/URL configuration). +
          def form_valid(self, form):
      +        """
      +        Add author and associated blog to form data before setting it as valid (so it is saved to model)
      +        """
      +        #Add logged-in user as author of comment
      +        form.instance.author = self.request.user
      +        #Associate comment with blog based on passed id
      +        form.instance.blog=get_object_or_404(Blog, pk = self.kwargs['pk'])
      +        # Call super-class form validation behaviour
      +        return super(BlogCommentCreate, self).form_valid(form)
      +
      +
    • +
    • You will need to provide a success URL to redirect to after the form validates; this should be the original blog. To do this you will need to override get_success_url() and "reverse" the URL for the original blog. You can get the required blog ID using the self.kwargs attribute, as shown in the form_valid() method above.
    • +
    +
  8. +
+ +

We briefly talked about passing a context to the template in a class-based view in the Django Tutorial Part 6: Generic list and detail views topic. To do this you need to override get_context_data() (first getting the existing context, updating it with whatever additional variables you want to pass to the template, and then returning the updated context). For example, the code fragment below shows how you can add a blogger object to the context based on their BlogAuthor id.

+ +
class SomeView(generic.ListView):
+    ...
+
+    def get_context_data(self, **kwargs):
+        # Call the base implementation first to get a context
+        context = super(SomeView, self).get_context_data(**kwargs)
+        # Get the blogger object from the "pk" URL parameter and add it to the context
+        context['blogger'] = get_object_or_404(BlogAuthor, pk = self.kwargs['pk'])
+        return context
+
+ +

Assessment

+ +

The assessment for this task is available on Github here. This assessment is primarily based on how well your application meets the requirements we listed above, though there are some parts of the assessment that check your code uses appropriate models, and that you have written at least some test code. When you're done, you can check out our the finished example which reflects a "full marks" project.

+ +

Once you've completed this module you've also finished all the MDN content for learning basic Django server-side website programming! We hope you enjoyed this module and feel you have a good grasp of the basics!

+ +

{{PreviousMenu("Learn/Server-side/Django/web_application_security", "Learn/Server-side/Django")}}

+ +

In this module

+ + diff --git a/files/zh-tw/learn/server-side/django/forms/index.html b/files/zh-tw/learn/server-side/django/forms/index.html new file mode 100644 index 0000000000..a4553d2d73 --- /dev/null +++ b/files/zh-tw/learn/server-side/django/forms/index.html @@ -0,0 +1,661 @@ +--- +title: 'Django Tutorial Part 9: Working with forms' +slug: Learn/Server-side/Django/Forms +translation_of: Learn/Server-side/Django/Forms +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Django/authentication_and_sessions", "Learn/Server-side/Django/Testing", "Learn/Server-side/Django")}}
+ +

在本教程中,我們將向您展示,如何在 Django 中使用 HTML 表單,特別是編寫表單以創建,更新和刪除模型實例的最簡單方法。作為本演示的一部分,我們將擴展 LocalLibrary 網站,以便圖書館員,可以使用我們自己的表單(而不是使用管理員應用程序)更新圖書,創建,更新和刪除作者。

+ + + + + + + + + + + + +
 前提:完成先前所有的教程, 包含 Django Tutorial Part 8: User authentication and permissions.
目的:了解如何製作表單來向用戶取得資訊並更新資料庫。了解通用類別表單編輯視圖 ( generic class-based form editing views ) 能夠大幅簡化用於單一模型的表單製作。
+ +

概述

+ +

HTML表單是網頁上的一組一個或多個字段/小組件,可用於從用戶收集信息以提交到服務器。 表單是一種用於收集用戶輸入的靈活機制,因為有合適的小部件可以輸入許多不同類型的數據,包括文本框,複選框,單選按鈕,日期選擇器等。表單也是與服務器共享數據的相對安全的方式, 因為它們允許我們在具有跨站點請求偽造保護的POST 請求中發送數據。

+ +

儘管到目前為止,本教程中尚未創建任何表單,但我們已經在Django Admin網站中遇到過這些表單-例如,下面的屏幕截圖顯示了一種用於編輯我們的Book 模型的表單,該表單由許多選擇列表和 文字編輯器。

+ +

Admin Site - Book Add

+ +

使用表單可能會很複雜!開發人員需要為表單編寫HTML,在服務器上(也可能在瀏覽器中)驗證並正確清理輸入的數據,使用錯誤消息重新發布表單以通知用戶任何無效字段,並在成功提交數據後處理數據,最後以某種方式回應用戶以表示成功。 Django表單通過提供一個框架使您能夠以編程方式定義表單及其字段,然後使用這些對像生成表單HTML代碼並處理許多驗證和用戶交互,從而完成了所有這些步驟中的大量工作。

+ +

在本教程中,我們將向您展示創建和使用表單的幾種方法,尤其是通用編輯表單視圖如何顯著減少創建表單來操縱表單所需的工作量。楷模。在此過程中,我們將擴展本地圖書館應用程序,方法是添加一個允許圖書館員續訂圖書的表格,並創建頁面以創建,編輯和刪除圖書和作者(複製上面顯示的表格的基本版本以編輯圖書) )。

+ +

HTML 表單

+ +

首先簡要介紹一下 HTML Forms。 考慮一個簡單的 HTML 表單,其中有一個用於輸入某些“團隊”名稱的文本字段及其相關標籤:

+ +

Simple name field example in HTML form

+ +

表單在HTML中定義為 <form>...</form> 標記內元素的集合,其中至少包含type="submit".的input元素。

+ +
<form action="/team_name_url/" method="post">
+    <label for="team_name">Enter name: </label>
+    <input id="team_name" type="text" name="name_field" value="Default name for team.">
+    <input type="submit" value="OK">
+</form>
+ +

雖然這裡只有一個用於輸入團隊名稱的文本字段,但是表單可以具有任意數量的其他輸入元素及其關聯的標籤。字段的type 屬性定義將顯示哪種小部件。字段的 nameid 用於標識JavaScript / CSS / HTML中的字段,而 value定義該字段在首次顯示時的初始值。匹配的團隊標籤是使用label 標籤指定的(請參見上面的“輸入名稱”),其中的  for 字段包含相關inputid 值。

+ +

submit 輸入將顯示為一個按鈕(默認情況下),用戶可以按下該按鈕以將表單中所有其他輸入元素中的數據上載到服務器(在這種情況下,僅是team_name)。表單屬性定義用於發送數據的HTTPmethod 以及服務器上數據的目的地(action):
+  

+ + + +

服務器的角色是首先呈現初始表單狀態-包含空白字段,或預填充初始值。用戶按下“提交”按鈕後,服務器將從Web瀏覽器接收帶有值的表單數據,並且必須驗證信息。如果表單包含無效數據,則服務器應再次顯示該表單,這一次將在“有效”字段中顯示用戶輸入的數據,並顯示描述無效字段問題的消息。服務器收到包含所有有效表單數據的請求後,便可以執行適當的操作(例如,保存數據,返回搜索結果,上傳文件等),然後通知用戶。

+ +

可以想像,創建HTML,驗證返回的數據,在需要時使用錯誤報告重新顯示輸入的數據以及對有效數據執行所需的操作都需要花費大量精力才能“正確”。 Django通過刪除一些繁瑣且重複的代碼,使此操作變得更加容易!

+ +

Django表單處理流程

+ +

Django的表單處理使用了我們在以前的教程中學到的所有相同技術(用於顯示有關模型的信息):視圖獲取請求,執行所需的任何操作,包括從模型中讀取數據,然後生成並返回HTML頁面( 從模板中,我們傳遞一個包含要顯示的數據的上下文)。 使事情變得更加複雜的是,服務器還需要能夠處理用戶提供的數據,並在出現任何錯誤時重新顯示頁面。

+ +

下面顯示了Django處理表單請求的過程流程圖,該流程圖從對包含表單的頁面的請求(以綠色顯示)開始。
+ Updated form handling process doc.

+ +

根據上圖,Django表單處理的主要功能是:

+ +
    +
  1. 在用戶第一次請求時顯示默認表單。 +
      +
    • 該表單可能包含空白字段(例如,如果您正在創建新記錄),或者可能會預先填充有初始值(例如,如果您正在更改記錄或具有有用的默認初始值)。
    • +
    • 由於此表單與任何用戶輸入的數據均不相關(儘管它可能具有初始值),因此在這一點上被稱為未綁定。
    • +
    +
  2. +
  3. 從提交請求中接收數據並將其綁定到表單。 +
      +
    • 將數據綁定到表單意味著當我們需要重新顯示表單時,用戶輸入的數據和任何錯誤均可用。
    • +
    +
  4. +
  5. 清理並驗證數據。 +
      +
    • 清理數據會對輸入執行清理操作(例如,刪除可能用於向服務器發送惡意內容的無效字符),並將其轉換為一致的Python類型。
    • +
    • 驗證會檢查該值是否適合該字段(例如,日期範圍正確,時間不要太短或太長等)
    • +
    +
  6. +
  7. 如果任何數據無效,則這次重新顯示該表單,其中包含用戶填充的所有值和問題字段的錯誤消息。
  8. +
  9. 如果所有數據均有效,請執行所需的操作(例如,保存數據,發送和發送電子郵件,返回搜索結果,上傳文件等)
  10. +
  11. 完成所有操作後,將用戶重定向到另一個頁面。
  12. +
+ +

Django提供了許多工具和方法來幫助您完成上述任務。 最基本的是 Form類,它簡化了表單HTML的生成和數據清除/驗證的過程。 在下一節中,我們將使用頁面的實際示例描述表單如何工作,以使圖書館員可以續訂書籍。

+ +
+

注意: 當我們討論Django的更多“高級”表單框架類時,了解Form的使用方式將對您有所幫助。

+
+ +

使用表單和功能視圖續訂表單

+ +

接下來,我們將添加一個頁面,以使圖書館員可以續借借來的書。 為此,我們將創建一個允許用戶輸入日期值的表單。 我們將從當前日期(正常藉閱期)起3週內為該字段提供初始值,並添加一些驗證以確保館員不能輸入過去的日期或將來的日期。 輸入有效日期後,我們會將其寫入當前記錄的BookInstance.due_back 字段中。

+ +

該示例將使用基於函數的視圖和Form 類。 以下各節說明表單的工作方式,以及您需要對正在進行的LocalLibrary項目進行的更改。

+ +

Form

+ +

Form類是Django表單處理系統的核心。 它指定表單中的字段,其佈局,顯示小部件,標籤,初始值,有效值,以及(一旦驗證)與無效字段關聯的錯誤消息。 該類還提供了使用預定義格式(表,列表等)在模板中呈現自身的方法,或用於獲取任何元素的值(啟用細粒度手動呈現)的方法。

+ +

申報表格

+ +

Form 的聲明語法與聲明Model的語法非常相似,並且具有相同的字段類型(和一些相似的參數)。 這是有道理的,因為在兩種情況下,我們都需要確保每個字段都處理正確的數據類型,被限制為有效數據並具有顯示/文檔描述。

+ +

要創建一個表單,我們導入Form 庫,從Form 類派生,並聲明表單的字段。 下面顯示了我們的圖書館圖書續訂表格的一個非常基本的表格類:

+ +
from django import forms
+
+class RenewBookForm(forms.Form):
+    renewal_date = forms.DateField(help_text="Enter a date between now and 4 weeks (default 3).")
+
+ +

Form fields

+ +

In this case we have a single DateField for entering the renewal date that will render in HTML with a blank value, the default label "Renewal date:", and some helpful usage text: "Enter a date between now and 4 weeks (default 3 weeks)." As none of the other optional arguments are specified the field will accept dates using the input_formats: YYYY-MM-DD (2016-11-06), MM/DD/YYYY (02/26/2016), MM/DD/YY (10/25/16), and will be rendered using the default widget: DateInput.

+ +

There are many other types of form fields, which you will largely recognise from their similarity to the equivalent model field classes: BooleanField, CharField, ChoiceField, TypedChoiceField, DateField, DateTimeField, DecimalField, DurationField, EmailField, FileField, FilePathField, FloatField, ImageField, IntegerField, GenericIPAddressField, MultipleChoiceField, TypedMultipleChoiceField, NullBooleanField, RegexField, SlugField, TimeField, URLField, UUIDField, ComboField, MultiValueField, SplitDateTimeField, ModelMultipleChoiceField, ModelChoiceField​​​​.

+ +

The arguments that are common to most fields are listed below (these have sensible default values):

+ + + +

Validation

+ +

Django provides numerous places where you can validate your data. The easiest way to validate a single field is to override the method clean_<fieldname>() for the field you want to check. So for example, we can validate that entered renewal_date values are between now and 4 weeks by implementing clean_renewal_date() as shown below.

+ +
from django import forms
+
+from django.core.exceptions import ValidationError
+from django.utils.translation import ugettext_lazy as _
+import datetime #for checking renewal date range.
+
+class RenewBookForm(forms.Form):
+    renewal_date = forms.DateField(help_text="Enter a date between now and 4 weeks (default 3).")
+
+    def clean_renewal_date(self):
+        data = self.cleaned_data['renewal_date']
+
+        #Check date is not in past.
+        if data < datetime.date.today():
+            raise ValidationError(_('Invalid date - renewal in past'))
+
+        #Check date is in range librarian allowed to change (+4 weeks).
+        if data > datetime.date.today() + datetime.timedelta(weeks=4):
+            raise ValidationError(_('Invalid date - renewal more than 4 weeks ahead'))
+
+        # Remember to always return the cleaned data.
+        return data
+ +

There are two important things to note. The first is that we get our data using self.cleaned_data['renewal_date'] and that we return this data whether or not we change it at the end of the function. This step gets us the data "cleaned" and sanitised of potentially unsafe input using the default validators, and converted into the correct standard type for the data (in this case a Python datetime.datetime object).

+ +

The second point is that if a value falls outside our range we raise a ValidationError, specifying the error text that we want to display in the form if an invalid value is entered. The example above also wraps this text in one of Django's translation functions ugettext_lazy() (imported as _()), which is good practice if you want to translate your site later.

+ +
+

Note: There are numerious other methods and examples for validating forms in Form and field validation (Django docs). For example, in cases where you have multiple fields that depend on each other, you can override the Form.clean() function and again raise a ValidationError.

+
+ +

That's all we need for the form in this example!

+ +

Copy the Form

+ +

Create and open the file locallibrary/catalog/forms.py and copy the entire code listing from the previous block into it.

+ +

URL Configuration

+ +

Before we create our view, let's add a URL configuration for the renew-books page. Copy the following configuration to the bottom of locallibrary/catalog/urls.py.

+ +
urlpatterns += [
+    path('book/<uuid:pk>/renew/', views.renew_book_librarian, name='renew-book-librarian'),
+]
+ +

The URL configuration will redirect URLs with the format /catalog/book/<bookinstance id>/renew/ to the function named renew_book_librarian() in views.py, and send the BookInstance id as the parameter named pk. The pattern only matches if pk is a correctly formatted uuid.

+ +
+

Note: We can name our captured URL data "pk" anything we like, because we have complete control over the view function (we're not using a generic detail view class that expects parameters with a certain name). However pk, short for "primary key", is a reasonable convention to use!

+
+ +

View

+ +

As discussed in the Django form handling process above, the view has to render the default form when it is first called and then either re-render it with error messages if the data is invalid, or process the data and redirect to a new page if the data is valid. In order to perform these different actions, the view has to be able to know whether it is being called for the first time to render the default form, or a subsequent time to validate data. 

+ +

For forms that use a POST request to submit information to the server, the most common pattern is for the view to test against the POST request type (if request.method == 'POST':) to identify form validation requests and GET (using an else condition) to identify the initial form creation request. If you want to submit your data using a GET request then a typical approach for identifying whether this is the first or subsequent view invocation is to read the form data (e.g. to read a hidden value in the form).

+ +

The book renewal process will be writing to our database, so by convention we use the POST request approach. The code fragment below shows the (very standard) pattern for this sort of function view. 

+ +
from django.shortcuts import get_object_or_404
+from django.http import HttpResponseRedirect
+from django.urls import reverse
+import datetime
+
+from .forms import RenewBookForm
+
+def renew_book_librarian(request, pk):
+    book_inst=get_object_or_404(BookInstance, pk = pk)
+
+    # If this is a POST request then process the Form data
+    if request.method == 'POST':
+
+        # Create a form instance and populate it with data from the request (binding):
+        form = RenewBookForm(request.POST)
+
+        # Check if the form is valid:
+        if form.is_valid():
+            # process the data in form.cleaned_data as required (here we just write it to the model due_back field)
+            book_inst.due_back = form.cleaned_data['renewal_date']
+            book_inst.save()
+
+            # redirect to a new URL:
+            return HttpResponseRedirect(reverse('all-borrowed') )
+
+    # If this is a GET (or any other method) create the default form.
+    else:
+        proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3)
+        form = RenewBookForm(initial={'renewal_date': proposed_renewal_date,})
+
+    return render(request, 'catalog/book_renew_librarian.html', {'form': form, 'bookinst':book_inst})
+ +

First we import our form (RenewBookForm) and a number of other useful objects/methods used in the body of the view function:

+ + + +

In the view we first use the pk argument in get_object_or_404() to get the current BookInstance (if this does not exist, the view will immediately exit and the page will display a "not found" error). If this is not a POST request (handled by the else clause) then we create the default form passing in an initial value for the renewal_date field (as shown in bold below, this is 3 weeks from the current date). 

+ +
    book_inst=get_object_or_404(BookInstance, pk = pk)
+
+    # If this is a GET (or any other method) create the default form
+    else:
+        proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3)
+        form = RenewBookForm(initial={'renewal_date': proposed_renewal_date,})
+
+    return render(request, 'catalog/book_renew_librarian.html', {'form': form, 'bookinst':book_inst})
+ +

After creating the form, we call render() to create the HTML page, specifying the template and a context that contains our form. In this case the context also contains our BookInstance, which we'll use in the template to provide information about the book we're renewing.

+ +

If however this is a POST request, then we create our form object and populate it with data from the request. This process is called "binding" and allows us to validate the form. We then check if the form is valid, which runs all the validation code on all of the fields — including both the generic code to check that our date field is actually a valid date and our specific form's clean_renewal_date() function to check the date is in the right range. 

+ +
    book_inst=get_object_or_404(BookInstance, pk = pk)
+
+    # If this is a POST request then process the Form data
+    if request.method == 'POST':
+
+        # Create a form instance and populate it with data from the request (binding):
+        form = RenewBookForm(request.POST)
+
+        # Check if the form is valid:
+        if form.is_valid():
+            # process the data in form.cleaned_data as required (here we just write it to the model due_back field)
+            book_inst.due_back = form.cleaned_data['renewal_date']
+            book_inst.save()
+
+            # redirect to a new URL:
+            return HttpResponseRedirect(reverse('all-borrowed') )
+
+    return render(request, 'catalog/book_renew_librarian.html', {'form': form, 'bookinst':book_inst})
+ +

If the form is not valid we call render() again, but this time the form value passed in the context will include error messages. 

+ +

If the form is valid, then we can start to use the data, accessing it through the form.cleaned_data attribute (e.g. data = form.cleaned_data['renewal_date']). Here we just save the data into the due_back value of the associated BookInstance object.

+ +
+

Important: While you can also access the form data directly through the request (for example request.POST['renewal_date'] or request.GET['renewal_date'] (if using a GET request) this is NOT recommended. The cleaned data is sanitised, validated, and converted into Python-friendly types.

+
+ +

The final step in the form-handling part of the view is to redirect to another page, usually a "success" page. In this case we use HttpResponseRedirect and reverse() to redirect to the view named 'all-borrowed' (this was created as the "challenge" in Django Tutorial Part 8: User authentication and permissions). If you didn't create that page consider redirecting to the home page at URL '/').

+ +

That's everything needed for the form handling itself, but we still need to restrict access to the view to librarians. We should probably create a new permission in BookInstance ("can_renew"), but to keep things simple here we just use the @permission_required function decorator with our existing can_mark_returned permission.

+ +

The final view is therefore as shown below. Please copy this into the bottom of locallibrary/catalog/views.py.

+ +
from django.contrib.auth.decorators import permission_required
+
+from django.shortcuts import get_object_or_404
+from django.http import HttpResponseRedirect
+from django.urls import reverse
+import datetime
+
+from .forms import RenewBookForm
+
+@permission_required('catalog.can_mark_returned')
+def renew_book_librarian(request, pk):
+    """
+    View function for renewing a specific BookInstance by librarian
+    """
+    book_inst=get_object_or_404(BookInstance, pk = pk)
+
+    # If this is a POST request then process the Form data
+    if request.method == 'POST':
+
+        # Create a form instance and populate it with data from the request (binding):
+        form = RenewBookForm(request.POST)
+
+        # Check if the form is valid:
+        if form.is_valid():
+            # process the data in form.cleaned_data as required (here we just write it to the model due_back field)
+            book_inst.due_back = form.cleaned_data['renewal_date']
+            book_inst.save()
+
+            # redirect to a new URL:
+            return HttpResponseRedirect(reverse('all-borrowed') )
+
+    # If this is a GET (or any other method) create the default form.
+    else:
+        proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3)
+        form = RenewBookForm(initial={'renewal_date': proposed_renewal_date,})
+
+    return render(request, 'catalog/book_renew_librarian.html', {'form': form, 'bookinst':book_inst})
+
+ +

The template

+ +

Create the template referenced in the view (/catalog/templates/catalog/book_renew_librarian.html) and copy the code below into it:

+ +
{% extends "base_generic.html" %}
+{% block content %}
+
+    <h1>Renew: \{{bookinst.book.title}}</h1>
+    <p>Borrower: \{{bookinst.borrower}}</p>
+    <p{% if bookinst.is_overdue %} class="text-danger"{% endif %}>Due date: \{{bookinst.due_back}}</p>
+
+    <form action="" method="post">
+        {% csrf_token %}
+        <table>
+        \{{ form }}
+        </table>
+        <input type="submit" value="Submit" />
+    </form>
+
+{% endblock %}
+ +

Most of this will be completely familiar from previous tutorials. We extend the base template and then redefine the content block. We are able to reference \{{bookinst}} (and its variables) because it was passed into the context object in the render() function, and we use these to list the book title, borrower and the original due date.

+ +

The form code is relatively simple. First we declare the form tags, specifying where the form is to be submitted (action) and the method for submitting the data (in this case an "HTTP POST") — if you recall the HTML Forms overview at the top of the page, an empty action as shown, means that the form data will be posted back to the current URL of the page (which is what we want!). Inside the tags we define the submit input, which a user can press to submit the data. The {% csrf_token %} added just inside the form tags is part of Django's cross-site forgery protection.

+ +
+

Note: Add the {% csrf_token %} to every Django template you create that uses POST to submit data. This will reduce the chance of forms being hijacked by malicious users.

+
+ +

All that's left is the \{{form}} template variable, which we passed to the template in the context dictionary. Perhaps unsurprisingly, when used as shown this provides the default rendering of all the form fields, including their labels, widgets, and help text — the rendering is as shown below:

+ +
<tr>
+  <th><label for="id_renewal_date">Renewal date:</label></th>
+  <td>
+    <input id="id_renewal_date" name="renewal_date" type="text" value="2016-11-08" required />
+    <br />
+    <span class="helptext">Enter date between now and 4 weeks (default 3 weeks).</span>
+  </td>
+</tr>
+
+ +
+

Note: It is perhaps not obvious because we only have one field, but by default every field is defined in its own table row (which is why the variable is inside table tags above).​​​​​​ This same rendering is provided if you reference the template variable \{{ form.as_table }}.

+
+ +

If you were to enter an invalid date, you'd additionally get a list of the errors rendered in the page (shown in bold below).

+ +
<tr>
+  <th><label for="id_renewal_date">Renewal date:</label></th>
+   <td>
+      <ul class="errorlist">
+        <li>Invalid date - renewal in past</li>
+      </ul>
+      <input id="id_renewal_date" name="renewal_date" type="text" value="2015-11-08" required />
+      <br />
+      <span class="helptext">Enter date between now and 4 weeks (default 3 weeks).</span>
+    </td>
+</tr>
+ +

Other ways of using form template variable

+ +

Using \{{form}} as shown above, each field is rendered as a table row. You can also render each field as a list item (using \{{form.as_ul}} ) or as a paragraph (using \{{form.as_p}}).

+ +

What is even more cool is that you can have complete control over the rendering of each part of the form, by indexing its properties using dot notation. So for example we can access a number of separate items for our renewal_date field:

+ + + +

For more examples of how to manually render forms in templates and dynamically loop over template fields, see Working with forms > Rendering fields manually (Django docs).

+ +

Testing the page

+ +

If you accepted the "challenge" in Django Tutorial Part 8: User authentication and permissions you'll have a list of all books on loan in the library, which is only visible to library staff. We can add a link to our renew page next to each item using the template code below.

+ +
{% if perms.catalog.can_mark_returned %}- <a href="{% url 'renew-book-librarian' bookinst.id %}">Renew</a>  {% endif %}
+ +
+

Note: Remember that your test login will need to have the permission "catalog.can_mark_returned" in order to access the renew book page (perhaps use your superuser account).

+
+ +

You can alternatively manually construct a test URL like this — http://127.0.0.1:8000/catalog/book/<bookinstance_id>/renew/ (a valid bookinstance id can be obtained by navigating to a book detail page in your library, and copying the id field).

+ +

What does it look like?

+ +

If you are successful, the default form will look like this:

+ +

+ +

The form with an invalid value entered, will look like this:

+ +

+ +

The list of all books with renew links will look like this:

+ +

+ +

ModelForms

+ +

Creating a Form class using the approach described above is very flexible, allowing you to create whatever sort of form page you like and associate it with any model or models.

+ +

However if you just need a form to map the fields of a single model then your model will already define most of the information that you need in your form: fields, labels, help text, etc. Rather than recreating the model definitions in your form, it is easier to use the ModelForm helper class to create the form from your model. This ModelForm can then be used within your views in exactly the same way as an ordinary Form.

+ +

A basic ModelForm containing the same field as our original RenewBookForm is shown below. All you need to do to create the form is add class Meta with the associated model (BookInstance) and a list of the model fields to include in the form (you can include all fields using fields = '__all__', or you can use exclude (instead of fields) to specify the fields not to include from the model).

+ +
from django.forms import ModelForm
+from .models import BookInstance
+
+class RenewBookModelForm(ModelForm):
+    class Meta:
+        model = BookInstance
+        fields = ['due_back',]
+
+ +
+

Note: This might not look like all that much simpler than just using a Form (and it isn't in this case, because we just have one field). However if you have a lot of fields, it can reduce the amount of code quite significantly!

+
+ +

The rest of the information comes from the model field definitions (e.g. labels, widgets, help text, error messages). If these aren't quite right, then we can override them in our class Meta, specifying a dictionary containing the field to change and its new value. For example, in this form we might want a label for our field of "Renewal date" (rather than the default based on the field name: Due date), and we also want our help text to be specific to this use case. The Meta below shows you how to override these fields, and you can similarly set widgets and error_messages if the defaults aren't sufficient.

+ +
class Meta:
+    model = BookInstance
+    fields = ['due_back',]
+    labels = { 'due_back': _('Renewal date'), }
+    help_texts = { 'due_back': _('Enter a date between now and 4 weeks (default 3).'), } 
+
+ +

To add validation you can use the same approach as for a normal Form — you define a function named clean_field_name() and raise ValidationError exceptions for invalid values. The only difference with respect to our original form is that the model field is named due_back and not "renewal_date".

+ +
from django.forms import ModelForm
+from .models import BookInstance
+
+class RenewBookModelForm(ModelForm):
+    def clean_due_back(self):
+       data = self.cleaned_data['due_back']
+
+       #Check date is not in past.
+       if data < datetime.date.today():
+           raise ValidationError(_('Invalid date - renewal in past'))
+
+       #Check date is in range librarian allowed to change (+4 weeks)
+       if data > datetime.date.today() + datetime.timedelta(weeks=4):
+           raise ValidationError(_('Invalid date - renewal more than 4 weeks ahead'))
+
+       # Remember to always return the cleaned data.
+       return data
+
+    class Meta:
+        model = BookInstance
+        fields = ['due_back',]
+        labels = { 'due_back': _('Renewal date'), }
+        help_texts = { 'due_back': _('Enter a date between now and 4 weeks (default 3).'), }
+
+ +

The class RenewBookModelForm below is now functionally equivalent to our original RenewBookForm. You could import and use it wherever you currently use RenewBookForm.

+ +

Generic editing views

+ +

The form handling algorithm we used in our function view example above represents an extremely common pattern in form editing views. Django abstracts much of this "boilerplate" for you, by creating generic editing views for creating, editing, and deleting views based on models. Not only do these handle the "view" behaviour, but they automatically create the form class (a ModelForm) for you from the model.

+ +
+

Note: In addition to the editing views described here, there is also a FormView class, which lies somewhere between our function view and the other generic views in terms of "flexibility" vs "coding effort". Using FormView you still need to create your Form, but you don't have to implement all of the standard form-handling pattern. Instead you just have to provide an implementation of the function that will be called once the submitted is known to be be valid.

+
+ +

In this section we're going to use generic editing views to create pages to add functionality to create, edit, and delete Author records from our library — effectively providing a basic reimplementation of parts of the Admin site (this could be useful if you need to offer admin functionality in a more flexible way that can be provided by the admin site).

+ +

Views

+ +

Open the views file (locallibrary/catalog/views.py) and append the following code block to the bottom of it:

+ +
from django.views.generic.edit import CreateView, UpdateView, DeleteView
+from django.urls import reverse_lazy
+from .models import Author
+
+class AuthorCreate(CreateView):
+    model = Author
+    fields = '__all__'
+    initial={'date_of_death':'05/01/2018',}
+
+class AuthorUpdate(UpdateView):
+    model = Author
+    fields = ['first_name','last_name','date_of_birth','date_of_death']
+
+class AuthorDelete(DeleteView):
+    model = Author
+    success_url = reverse_lazy('authors')
+ +

As you can see, to create the views you need to derive from CreateView, UpdateView, and DeleteView (respectively) and then define the associated model.

+ +

For the "create" and "update" cases you also need to specify the fields to display in the form (using in same syntax as for ModelForm). In this case we show both the syntax to display "all" fields, and how you can list them individually. You can also specify initial values for each of the fields using a dictionary of field_name/value pairs (here we arbitrarily set the date of death for demonstration purposes — you might want to remove that!). By default these views will redirect on success to a page displaying the newly created/edited model item, which in our case will be the author detail view we created in a previous tutorial. You can specify an alternative redirect location by explicitly declaring parameter success_url (as done for the AuthorDelete class).

+ +

The AuthorDelete class doesn't need to display any of the fields, so these don't need to be specified. You do however need to specify the success_url, because there is no obvious default value for Django to use. In this case we use the reverse_lazy() function to redirect to our author list after an author has been deleted — reverse_lazy() is a lazily executed version of reverse(), used here because we're providing a URL to a class-based view attribute.

+ +

Templates

+ +

The "create" and "update" views use the same template by default, which will be named after your model: model_name_form.html (you can change the suffix to something other than _form using the template_name_suffix field in your view, e.g. template_name_suffix = '_other_suffix')

+ +

Create the template file locallibrary/catalog/templates/catalog/author_form.html and copy in the text below.

+ +
{% extends "base_generic.html" %}
+
+{% block content %}
+
+<form action="" method="post">
+    {% csrf_token %}
+    <table>
+    \{{ form.as_table }}
+    </table>
+    <input type="submit" value="Submit" />
+
+</form>
+{% endblock %}
+ +

This is similar to our previous forms, and renders the fields using a table. Note also how again we declare the {% csrf_token %} to ensure that our forms are resistant to CSRF attacks.

+ +

The "delete" view expects to find a template named with the format model_name_confirm_delete.html (again, you can change the suffix using template_name_suffix in your view). Create the template file locallibrary/catalog/templates/catalog/author_confirm_delete.html and copy in the text below.

+ +
{% extends "base_generic.html" %}
+
+{% block content %}
+
+<h1>Delete Author</h1>
+
+<p>Are you sure you want to delete the author: \{{ author }}?</p>
+
+<form action="" method="POST">
+  {% csrf_token %}
+  <input type="submit" action="" value="Yes, delete." />
+</form>
+
+{% endblock %}
+
+ +

URL configurations

+ +

Open your URL configuration file (locallibrary/catalog/urls.py) and add the following configuration to the bottom of the file:

+ +
urlpatterns += [
+    path('author/create/', views.AuthorCreate.as_view(), name='author_create'),
+    path('author/<int:pk>/update/', views.AuthorUpdate.as_view(), name='author_update'),
+    path('author/<int:pk>/delete/', views.AuthorDelete.as_view(), name='author_delete'),
+]
+ +

There is nothing particularly new here! You can see that the views are classes, and must hence be called via .as_view(), and you should be able to recognise the URL patterns in each case. We must use pk as the name for our captured primary key value, as this is the parameter name expected by the view classes.

+ +

The author create, update, and delete pages are now ready to test (we won't bother hooking them into the site sidebar in this case, although you can do so if you wish).

+ +
+

Note: Observant users will have noticed that we didn't do anything to prevent unauthorised users from accessing the pages! We leave that as an exercise for you (hint: you could use the PermissionRequiredMixin and either create a new permission or reuse our can_mark_returned permission).

+
+ +

Testing the page

+ +

First login to the site with an account that has whatever permissions you decided are needed to access the author editing pages.

+ +

Then navigate to the author create page: http://127.0.0.1:8000/catalog/author/create/, which should look like the screenshot below.

+ +

Form Example: Create Author

+ +

Enter values for the fields and then press Submit to save the author record. You should now be taken to a detail view for your new author, with a URL of something like http://127.0.0.1:8000/catalog/author/10.

+ +

You can test editing records by appending /update/ to the end of the detail view URL (e.g. http://127.0.0.1:8000/catalog/author/10/update/) — we don't show a screenshot, because it looks just like the "create" page!

+ +

Last of all we can delete the page, by appending delete to the end of the author detail-view URL (e.g. http://127.0.0.1:8000/catalog/author/10/delete/). Django should display the delete page shown below. Press Yes, delete. to remove the record and be taken to the list of all authors.

+ +

+ +

Challenge yourself

+ +

Create some forms to create, edit and delete Book records. You can use exactly the same structure as for Authors. If your book_form.html template is just a copy-renamed version of the author_form.html template, then the new "create book" page will look like the screenshot below:

+ +

+ + + +

Summary

+ +

Creating and handling forms can be a complicated process! Django makes it much easier by providing programmatic mechanisms to declare, render and validate forms. Furthermore, Django provides generic form editing views that can do almost all the work to define pages that can create, edit, and delete records associated with a single model instance.

+ +

There is a lot more that can be done with forms (check out our See also list below), but you should now understand how to add basic forms and form-handling code to your own websites.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/Server-side/Django/authentication_and_sessions", "Learn/Server-side/Django/Testing", "Learn/Server-side/Django")}}

+ +

In this module

+ + diff --git a/files/zh-tw/learn/server-side/django/generic_views/index.html b/files/zh-tw/learn/server-side/django/generic_views/index.html new file mode 100644 index 0000000000..240354cd6b --- /dev/null +++ b/files/zh-tw/learn/server-side/django/generic_views/index.html @@ -0,0 +1,612 @@ +--- +title: 'Django Tutorial Part 6: Generic list and detail views' +slug: Learn/Server-side/Django/Generic_views +translation_of: Learn/Server-side/Django/Generic_views +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Django/Home_page", "Learn/Server-side/Django/Sessions", "Learn/Server-side/Django")}}
+ +

本教程擴充了 LocalLibrary 網站,為書本與作者增加列表與細節頁面。此處我們將學到通用類別視圖,並演示如何降低你必須為一般使用案例撰寫的程式碼數量。我們也會更加深入 URL 處理細節,演示如何實施基本模式匹配。

+ + + + + + + + + + + + +
前提:Complete all previous tutorial topics, including Django Tutorial Part 5: Creating our home page.
目的:To understand where and how to use generic class-based views, and how to extract patterns from URLs and pass the information to views.
+ +

Overview

+ +

本教程中,通過為書本和作者添加列表和詳細信息頁面,我們將完成第一個版本的 LocalLibrary 網站(或者更準確地說,我們將向您展示如何實現書頁,並讓您自己創建作者頁面!) )

+ +

該過程在創建索引頁面,我們在上一個教程中展示了該頁面。我們仍然需要創建URL地圖,視圖和模板。主要區別在於,對於詳細信息頁面,我們還有一個額外的挑戰,即從URL對於這些頁面,我們將演示一種完全不同的視圖類型:基於類別的通用列表和詳細視圖。這些可以顯著減少所需的視圖代碼量,有助於更容易編寫和維護。

+ +

本教程的最後一部分,將演示在使用基於類別的通用列表視圖時,如何對數據進行分頁。

+ +

Book list page

+ +

該書將顯示每條記錄的標題和作者,標題是指向相關圖書詳細信息頁面的超鏈接。該頁面將具有與站點中,所有其他頁面相同的結構和導航,因此,我們可以擴展在上一個教程中創建的基本模板 (base_generic.html)。

+ +

URL mapping

+ +

開啟/catalog/urls.py,並複製加入下面粗體顯示的代碼。就像索引頁面的方式,這個path()函數,定義了一個與URL匹配的模式('books /'),如果URL匹配,將調用視圖函數(views.BookListView.as_view())和一個對應的特定映射的名稱。

+ +
urlpatterns = [
+    path('', views.index, name='index'),
+    path('books/', views.BookListView.as_view(), name='books'),
+]
+ +

正如前一個教程中所討論的,URL必須已經先匹配了/ catalog,因此實際上將為URL調用的視圖是:/ catalog / books /。

+ +

我們將繼承現有的泛型視圖函數,該函數已經完成了我們希望此視圖函數執行的大部分工作,而不是從頭開始編寫自己的函數。對於基於Django類的視圖,我們通過調用類方法as_view(),來訪問適當的視圖函數。由此可以創建類的實例,並確保為HTTP請求正確的處理程序方法。

+ +

View (class-based)

+ +

我們可以很容易地,將書本列表列表編寫為常規函數(就像我們之前的索引視圖一樣),進入查詢數據庫中的所有書本,然後調用render(),將列表傳遞給指定的模板。然而,我們用另一種方​​法取代,我們將使用基於類的通用列表視圖(ListView)-一個繼承自現有視圖的類。因為通用視圖,已經實現了我們需要的大部分功能,並且遵循Django最佳實踐,我們將能夠創建更強大的列表視圖,代碼更多,重複次數最多,最終維護所需。

+ +

開啟catalog / views.py,將以下代碼複製到文件的底部:

+ +
from django.views import generic
+
+class BookListView(generic.ListView):
+    model = Book
+ +

就是這樣!通用view將查詢數據庫,以獲取指定模型(Book)的所有記錄,然後呈現/locallibrary/catalog/templates/catalog/book_list.html的模板(我們將在下面創建)。在模板中,您可以使用所謂的object_list或book_list的模板變量(即通常為“ the_model_name_list”),以訪問書本列表。

+ +
+

Note: This awkward path for the template location isn't a misprint — the generic views look for templates in /application_name/the_model_name_list.html (catalog/book_list.html in this case) inside the application's /application_name/templates/ directory (/catalog/templates/).

+
+ +

您可以添加屬性,以更改上面的某種行為。例如,如果需要使用同一模型的多個視圖,則可以指定另一個模板文件,或者如果book_list對於特定模板用例不直觀,則可能需要使用不同的模板變量名稱。可能最有用的變更,是更改/過濾返回的結果子集-因此,您可能會列出其他用戶閱讀的前5本書,而不是列出所有書本。

+ +
class BookListView(generic.ListView):
+    model = Book
+    context_object_name = 'my_book_list'   # your own name for the list as a template variable
+    queryset = Book.objects.filter(title__icontains='war')[:5] # Get 5 books containing the title war
+    template_name = 'books/my_arbitrary_template_name_list.html'  # Specify your own template name/location
+ +

Overriding methods in class-based views

+ +

雖然我們不需要在這裡執行此操作,但您也可以覆寫某些類別方法。

+ +

例如,我們可以覆寫get_queryset()方法,來更改返回的記錄列表。這比單獨設置queryset屬性更靈活,就像我們在前面的代碼片段中進行的那樣(儘管在這案例中沒有太大用處):

+ +
class BookListView(generic.ListView):
+    model = Book
+
+    def get_queryset(self):
+        return Book.objects.filter(title__icontains='war')[:5] # Get 5 books containing the title war
+
+ +

我們還可以重寫get_context_data() 以便將其他上下文變數傳遞給模組 (例如,默認情況下傳遞書籍列表). 下面的片段顯示瞭如何向上下文添加名為"some_data" 的變數(然後它將用作模組變數)

+ +
class BookListView(generic.ListView):
+    model = Book
+
+    def get_context_data(self, **kwargs):
+        # Call the base implementation first to get the context
+        context = super(BookListView, self).get_context_data(**kwargs)
+        # Create any data and add it to the context
+        context['some_data'] = 'This is just some data'
+        return context
+ +

執行此操作時,務必遵循上面使用的模式:

+ + + +
+

Note: Check out Built-in class-based generic views (Django docs) for many more examples of what you can do.

+
+ +

Creating the List View template

+ +

建立HTML及複製以下文字串到/locallibrary/catalog/templates/catalog/book_list.html , 這是基於通用類的列表視圖所期望的默認模板文件 (默認在catalog中名稱為Book 的模組).

+ +

通用的views模板跟其他的模板沒有不同 (儘管傳遞給模板的內文/訊息當然可以不同). 與index模板一樣,我們在第一行中擴展了基本模板,然後更替名為 content的區塊。

+ +
{% extends "base_generic.html" %}
+
+{% block content %}
+  <h1>Book List</h1>
+  {% if book_list %}
+  <ul>
+    {% for book in book_list %}
+      <li>
+        <a href="\{{ book.get_absolute_url }}">\{{ book.title }}</a> (\{{book.author}})
+      </li>
+    {% endfor %}
+  </ul>
+  {% else %}
+    <p>There are no books in the library.</p>
+  {% endif %} 
+{% endblock %}
+ +

該視圖默認將上下文(書籍列表)作為object_list 和 book_list 別名傳遞;兩者都會起作用.

+ +

Conditional execution

+ +

我們使用 if, else 和 endif 模組標籤,以檢查book_list 是否已定義並且不為空。 如果 book_list 為空值, 則 else 子句回傳text 說明沒有書可以列出. 如果book_list不是空值, 然後我們遍曆書籍清單。

+ +
{% if book_list %}
+  <!-- code here to list the books -->
+{% else %}
+  <p>There are no books in the library.</p>
+{% endif %}
+
+ +

The condition above only checks for one case, but you can test on additional conditions using the elif template tag (e.g. {% elif var2 %} ). For more information about conditional operators see: if, ifequal/ifnotequal, and ifchanged in Built-in template tags and filters (Django Docs).

+ +

For loops

+ +

The template uses the for and endfor template tags to loop through the book list, as shown below. Each iteration populates the book template variable with information for the current list item.

+ +
{% for book in book_list %}
+  <li> <!-- code here get information from each book item --> </li>
+{% endfor %}
+
+ +

While not used here, within the loop Django will also create other variables that you can use to track the iteration. For example, you can test the forloop.last variable to perform conditional processing the last time that the loop is run.

+ +

Accessing variables

+ +

The code inside the loop creates a list item for each book that shows both the title (as a link to the yet-to-be-created detail view) and the author.

+ +
<a href="\{{ book.get_absolute_url }}">\{{ book.title }}</a> (\{{book.author}})
+
+ +

We access the fields of the associated book record using the "dot notation" (e.g. book.title and book.author), where the text following the book item is the field name (as defined in the model).

+ +

We can also call functions in the model from within our template — in this case we call Book.get_absolute_url() to get an URL you could use to display the associated detail record. This works provided the function does not have any arguments (there is no way to pass arguments!)

+ +
+

Note: We have to be a little careful of "side effects" when calling functions in templates. Here we just get a URL to display, but a function can do pretty much anything — we wouldn't want to delete our database (for example) just by rendering our template!

+
+ +

Update the base template

+ +

Open the base template (/locallibrary/catalog/templates/base_generic.html) and insert {% url 'books' %} into the URL link for All books, as shown below. This will enable the link in all pages (we can successfully put this in place now that we've created the "books" url mapper).

+ +
<li><a href="{% url 'index' %}">Home</a></li>
+<li><a href="{% url 'books' %}">All books</a></li>
+<li><a href="">All authors</a></li>
+ +

What does it look like?

+ +

You won't be able to build book list yet, because we're still missing a dependency — the URL map for the book detail pages, which is needed to create hyperlinks to individual books. We'll show both list and detail views after the next section.

+ +

Book detail page

+ +

The book detail page will display information about a specific book, accessed using the URL catalog/book/<id> (where <id> is the primary key for the book). In addition to fields in the Book model (author, summary, ISBN, language, and genre), we'll also list the details of the available copies (BookInstances) including the status, expected return date, imprint, and id. This will allow our readers not just to learn about the book, but also to confirm whether/when it is available.

+ +

URL mapping

+ +

Open /catalog/urls.py and add the 'book-detail' URL mapper shown in bold below. This path() function defines a pattern, associated generic class-based detail view, and a name.

+ +
urlpatterns = [
+    path('', views.index, name='index'),
+    path('books/', views.BookListView.as_view(), name='books'),
+    path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'),
+]
+ +

For the book-detail path the URL pattern uses a special syntax to capture the specific id of the book that we want to see. The syntax is very simple: angle brackets define the part of the URL to be captured, enclosing the name of the variable that the view can use to access the captured data. For example, <something> , will capture the marked pattern and pass the value to the view as a variable "something". You can optionally precede the variable name with a converter specification that defines the type of data (int, str, slug, uuid, path).

+ +

In this case we use '<int:pk>'  to capture the book id, which must be an integer, and pass it to the view as a parameter named pk (short for primary key).

+ +
+

Note: As discussed previously, our matched URL is actually catalog/book/<digits> (because we are in the catalog application, /catalog/ is assumed).

+
+ +
+

Important: The generic class-based detail view expects to be passed a parameter named pk. If you're writing your own function view you can use whatever parameter name you like, or indeed pass the information in an unnamed argument.

+
+ +

Advanced path matching/regular expression primer

+ +
+

Note: You won't need this section to complete the tutorial! We provide it because knowing this option is likely to be useful in your Django-centric future.

+
+ +

The pattern matching provided by path() is simple and useful for the (very common) cases where you just want to capture any string or integer. If you need more refined filtering (for example, to filter only strings that have a certain number of characters) then you can use the re_path() method.

+ +

This method is used just like path() except that it allows you to specify a pattern using a Regular expression. For example, the previous path could have been written as shown below:

+ +
re_path(r'^book/(?P<pk>\d+)$', views.BookDetailView.as_view(), name='book-detail'),
+
+ +

Regular expressions are an incredibly powerful pattern mapping tool. They are, frankly, quite unintuitive and scary for beginners. Below is a very short primer!

+ +

The first thing to know is that regular expressions should usually be declared using the raw string literal syntax (i.e. they are enclosed as shown: r'<your regular expression text goes here>').

+ +

The main parts of the syntax you will need to know for declaring the pattern matches are:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SymbolMeaning
^Match the beginning of the text
$Match the end of the text
\dMatch a digit (0, 1, 2, ... 9)
\wMatch a word character, e.g. any upper- or lower-case character in the alphabet, digit or the underscore character (_)
+Match one or more of the preceding character. For example, to match one or more digits you would use \d+. To match one or more "a" characters, you could use a+
*Match zero or more of the preceding character. For example, to match nothing or a word you could use \w*
( )Capture the part of the pattern inside the brackets. Any captured values will be passed to the view as unnamed parameters (if multiple patterns are captured, the associated parameters will be supplied in the order that the captures were declared).
(?P<name>...)Capture the pattern (indicated by ...) as a named variable (in this case "name"). The captured values are passed to the view with the name specified. Your view must therefore declare an argument with the same name!
[  ]Match against one character in the set. For example, [abc] will match on 'a' or 'b' or 'c'. [-\w] will match on the '-' character or any word character.
+ +

Most other characters can be taken literally!

+ +

Lets consider a few real examples of patterns:

+ + + + + + + + + + + + + + + + + + + + + + +
PatternDescription
r'^book/(?P<pk>\d+)$' +

This is the RE used in our url mapper. It matches a string that has book/ at the start of the line (^book/), then has one or more digits (\d+), and then ends (with no non-digit characters before the end of line marker).

+ +

It also captures all the digits (?P<pk>\d+) and passes them to the view in a parameter named 'pk'. The captured values are always passed as a string!

+ +

For example, this would match book/1234 , and send a variable pk='1234' to the view.

+
r'^book/(\d+)$'This matches the same URLs as the preceding case. The captured information would be sent as an unnamed argument to the view.
r'^book/(?P<stub>[-\w]+)$' +

This matches a string that has book/ at the start of the line (^book/), then has one or more characters that are either a '-' or a word character ([-\w]+), and then ends. It also captures this set of characters and passes them to the view in a parameter named 'stub'.

+ +

This is a fairly typical pattern for a "stub". Stubs are URL-friendly word-based primary keys for data. You might use a stub if you wanted your book URL to be more informative. For example /catalog/book/the-secret-garden rather than /catalog/book/33.

+
+ +

You can capture multiple patterns in the one match, and hence encode lots of different information in a URL.

+ +
+

Note: As a challenge, consider how you might encode an url to list all books released in a particular year, month, day, and the RE that could be used to match it.

+
+ +

Passing additional options in your URL maps

+ +

One feature that we haven't used here, but which you may find valuable, is that you can declare and pass additional options to the view. The options are declared as a dictionary that you pass as the third un-named argument to the path() function. This approach can be useful if you want to use the same view for multiple resources, and pass data to configure its behaviour in each case (below we supply a different template in each case).

+ +
path('url/', views.my_reused_view, {'my_template_name': 'some_path'}, name='aurl'),
+path('anotherurl/', views.my_reused_view, {'my_template_name': 'another_path'}, name='anotherurl'),
+
+ +
+

Note: Both extra options and named captured patterns are passed to the view as named arguments. If you use the same name for both a captured pattern and an extra option then only the captured pattern value will be sent to the view (the value specified in the additional option will be dropped). 

+
+ +

View (class-based)

+ +

Open catalog/views.py, and copy the following code into the bottom of the file:

+ +
class BookDetailView(generic.DetailView):
+    model = Book
+ +

That's it! All you need to do now is create a template called /locallibrary/catalog/templates/catalog/book_detail.html, and the view will pass it the database information for the specific Book record extracted by the URL mapper. Within the template you can access the list of books with the template variable named object OR book (i.e. generically "the_model_name").

+ +

If you need to, you can change the template used and the name of the context object used to reference the book in the template. You can also override methods to, for example, add additional information to the context.

+ +

What happens if the record doesn't exist?

+ +

If a requested record does not exist then the generic class-based detail view will raise an Http404 exception for you automatically — in production this will automatically display an appropriate "resource not found" page, which you can customise if desired.

+ +

Just to give you some idea of how this works, the code fragment below demonstrates how you would implement the class-based view as a function, if you were not using the generic class-based detail view.

+ +
def book_detail_view(request, primary_key):
+    try:
+        book = Book.objects.get(pk=primary_key)
+    except Book.DoesNotExist:
+        raise Http404('Book does not exist')
+
+    # from django.shortcuts import get_object_or_404
+    # book = get_object_or_404(Book, pk=primary_key)
+
+    return render(request, 'catalog/book_detail.html', context={'book': book})
+
+ +

The view first tries to get the specific book record from the model. If this fails the view should raise an Http404 exception to indicate that the book is "not found". The final step is then, as usual, to call render() with the template name and the book data in the context parameter (as a dictionary).

+ +
+

Note: The get_object_or_404() (shown commented out above) is a convenient shortcut to raise an Http404 exception if the record is not found.

+
+ +

Creating the Detail View template

+ +

Create the HTML file /locallibrary/catalog/templates/catalog/book_detail.html and give it the below content. As discussed above, this is the default template file name expected by the generic class-based detail view (for a model named Book in an application named catalog).

+ +
{% extends "base_generic.html" %}
+
+{% block content %}
+  <h1>Title: \{{ book.title }}</h1>
+
+  <p><strong>Author:</strong> <a href="">\{{ book.author }}</a></p> <!-- author detail link not yet defined -->
+  <p><strong>Summary:</strong> \{{ book.summary }}</p>
+  <p><strong>ISBN:</strong> \{{ book.isbn }}</p>
+  <p><strong>Language:</strong> \{{ book.language }}</p>
+  <p><strong>Genre:</strong> {% for genre in book.genre.all %} \{{ genre }}{% if not forloop.last %}, {% endif %}{% endfor %}</p>
+
+  <div style="margin-left:20px;margin-top:20px">
+    <h4>Copies</h4>
+
+    {% for copy in book.bookinstance_set.all %}
+    <hr>
+    <p class="{% if copy.status == 'a' %}text-success{% elif copy.status == 'm' %}text-danger{% else %}text-warning{% endif %}">\{{ copy.get_status_display }}</p>
+    {% if copy.status != 'a' %}<p><strong>Due to be returned:</strong> \{{copy.due_back}}</p>{% endif %}
+    <p><strong>Imprint:</strong> \{{copy.imprint}}</p>
+    <p class="text-muted"><strong>Id:</strong> \{{copy.id}}</p>
+    {% endfor %}
+  </div>
+{% endblock %}
+ + + +
+

The author link in the template above has an empty URL because we've not yet created an author detail page. Once that exists, you should update the URL like this:

+ +
<a href="{% url 'author-detail' book.author.pk %}">\{{ book.author }}</a>
+
+
+ +

Though a little larger, almost everything in this template has been described previously:

+ + + +

The one interesting thing we haven't seen before is the function book.bookinstance_set.all(). This method is "automagically" constructed by Django in order to return the set of BookInstance records associated with a particular Book.

+ +
{% for copy in book.bookinstance_set.all %}
+<!-- code to iterate across each copy/instance of a book -->
+{% endfor %}
+ +

需要這方法是因為我們僅在“一”那側model(Book)定義一個ForeignKey (一對多)字段的關聯,也因為沒有任何的關聯被定義在“多”那側model(BookInstance),故無法透過字段來取得相關的紀錄。為了克服這個問題,Django建立一個function取名為“reverse lookup”供使用。function的名字以一對多關係中該 ForeignKey 被定義在的那個模型名稱小寫,再在字尾加上_set(因此在 Book 創建的function名是 bookinstance_set())。

+ +
+

Note: 在這我們使用 all() 取得所有紀錄 (預設),你無法直接在template做是因為你無法指定引數到function,但你可用 filter() 方法取得一個紀錄的子集 。

+ +

順帶一提,若你不再基於類的view或model定義順序(order),開發伺服器會將會報錯類似的訊息:

+ +
[29/May/2017 18:37:53] "GET /catalog/books/?page=1 HTTP/1.1" 200 1637
+/foo/local_library/venv/lib/python3.5/site-packages/django/views/generic/list.py:99: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <QuerySet [<Author: Ortiz, David>, <Author: H. McRaven, William>, <Author: Leigh, Melinda>]>
+  allow_empty_first_page=allow_empty_first_page, **kwargs)
+
+ +

That happens because the paginator object expects to see some ORDER BY being executed on your underlying database. Without it, it can't be sure the records being returned are actually in the right order!

+ +

This tutorial didn't reach Pagination (yet, but soon enough), but since you can't use sort_by() and pass a parameter (the same with filter() described above) you will have to choose between three choices:

+ +
    +
  1. Add a ordering inside a class Meta declaration on your model.
  2. +
  3. Add a queryset attribute in your custom class-based view, specifying a order_by().
  4. +
  5. Adding a get_queryset method to your custom class-based view and also specify the order_by().
  6. +
+ +

If you decide to go with a class Meta for the Author model (probably not as flexible as customizing the class-based view, but easy enough), you will end up with something like this:

+ +
class Author(models.Model):
+    first_name = models.CharField(max_length=100)
+    last_name = models.CharField(max_length=100)
+    date_of_birth = models.DateField(null=True, blank=True)
+    date_of_death = models.DateField('Died', null=True, blank=True)
+
+    def get_absolute_url(self):
+        return reverse('author-detail', args=[str(self.id)])
+
+    def __str__(self):
+        return f'{self.last_name}, {self.first_name}'
+
+    class Meta:
+        ordering = ['last_name']
+ +

Of course, the field doesn't need to be last_name: it could be any other.

+ +

And last, but not least, you should sort by an attribute/column that actually has a index (unique or not) on your database to avoid performance issues. Of course, this will not be necessary here (and we are probably getting ourselves too much ahead) if such small amount of books (and users!), but it is something to keep in mind for future projects.

+
+ +

What does it look like?

+ +

At this point we should have created everything needed to display both the book list and book detail pages. Run the server (python3 manage.py runserver) and open your browser to http://127.0.0.1:8000/.

+ +
+

Warning: Don't click any author or author detail links yet — you'll create those in the challenge!

+
+ +

Click the All books link to display the list of books. 

+ +

Book List Page

+ +

Then click a link to one of your books. If everything is set up correctly, you should see something like the following screenshot.

+ +

Book Detail Page

+ +

Pagination

+ +

If you've just got a few records, our book list page will look fine. However, as you get into the tens or hundreds of records the page will take progressively longer to load (and have far too much content to browse sensibly). The solution to this problem is to add pagination to your list views, reducing the number of items displayed on each page. 

+ +

Django has excellent in-built support for pagination. Even better, this is built into the generic class-based list views so you don't have to do very much to enable it!

+ +

Views

+ +

Open catalog/views.py, and add the paginate_by line shown in bold below.

+ +
class BookListView(generic.ListView):
+    model = Book
+    paginate_by = 10
+ +

With this addition, as soon as you have more than 10 records the view will start paginating the data it sends to the template. The different pages are accessed using GET parameters — to access page 2 you would use the URL: /catalog/books/?page=2.

+ +

Templates

+ +

Now that the data is paginated, we need to add support to the template to scroll through the results set. Because we might want to do this in all list views, we'll do this in a way that can be added to the base template. 

+ +

Open /locallibrary/catalog/templates/base_generic.html and copy in the following pagination block below our content block (highlighted below in bold). The code first checks if pagination is enabled on the current page. If so then it adds next and previous links as appropriate (and the current page number). 

+ +
{% block content %}{% endblock %}
+
+{% block pagination %}
+  {% if is_paginated %}
+    <div class="pagination">
+      <span class="page-links">
+        {% if page_obj.has_previous %}
+          <a href="\{{ request.path }}?page=\{{ page_obj.previous_page_number }}">previous</a>
+        {% endif %}
+        <span class="page-current">
+          <p>Page \{{ page_obj.number }} of \{{ page_obj.paginator.num_pages }}.</p>
+        </span>
+        {% if page_obj.has_next %}
+          <a href="\{{ request.path }}?page=\{{ page_obj.next_page_number }}">next</a>
+        {% endif %}
+      </span>
+    </div>
+  {% endif %}
+{% endblock %} 
+ +

The page_obj is a Paginator object that will exist if pagination is being used on the current page. It allows you to get all the information about the current page, previous pages, how many pages there are, etc. 

+ +

We use \{{ request.path }} to get the current page URL for creating the pagination links. This is useful, because it is independent of the object that we're paginating.

+ +

Thats it!

+ +

What does it look like?

+ +

The screenshot below shows what the pagination looks like — if you haven't entered more than 10 titles into your database, then you can test it more easily by lowering the number specified in the paginate_by line in your catalog/views.py file. To get the below result we changed it to paginate_by = 2.

+ +

The pagination links are displayed on the bottom, with next/previous links being displayed depending on which page you're on.

+ +

Book List Page - paginated

+ +

Challenge yourself

+ +

The challenge in this article is to create the author detail and list views required to complete the project. These should be made available at the following URLs:

+ + + +

The code required for the URL mappers and the views should be virtually identical to the Book list and detail views we created above. The templates will be different, but will share similar behaviour.

+ +
+

Note:

+ + +
+ +

When you are finished, your pages should look something like the screenshots below.

+ +

Author List Page

+ + + +

Author Detail Page

+ + + +

Summary

+ +

Congratulations, our basic library functionality is now complete! 

+ +

In this article we've learned how to use the generic class-based list and detail views and used them to create pages to view our books and authors. Along the way we've learned about pattern matching with regular expressions, and how you can pass data from URLs to your views. We've also learned a few more tricks for using templates. Last of all we've shown how to paginate list views, so that our lists are managable even when we have many records.

+ +

In our next articles we'll extend this library to support user accounts, and thereby demonstrate user authentication, permissons, sessions, and forms.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/Server-side/Django/Home_page", "Learn/Server-side/Django/Sessions", "Learn/Server-side/Django")}}

+ +

In this module

+ + diff --git a/files/zh-tw/learn/server-side/django/home_page/index.html b/files/zh-tw/learn/server-side/django/home_page/index.html new file mode 100644 index 0000000000..a01d71608e --- /dev/null +++ b/files/zh-tw/learn/server-side/django/home_page/index.html @@ -0,0 +1,383 @@ +--- +title: 'Django Tutorial Part 5: Creating our home page' +slug: Learn/Server-side/Django/Home_page +translation_of: Learn/Server-side/Django/Home_page +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Django/Admin_site", "Learn/Server-side/Django/Generic_views", "Learn/Server-side/Django")}}
+ +

我們現在可以添加代碼,來顯示我們的第一個完整頁面 - LocalLibrary 網站的主頁,顯示每個模型類型有多少條記錄,並提供我們其他頁面的側邊欄導航鏈接。一路上,我們將獲得編寫基本URL 地圖和視圖、從數據庫獲取記錄、以及使用模板的實踐經驗。

+ + + + + + + + + + + + +
前提:讀 the Django Introduction. 完成上章節 (including Django Tutorial Part 4: Django admin site).
目的:了解如何創建簡單的URL映射和視圖(沒有數據編碼在URL中)以及如何從模型中獲取數據並創建模版。
+ 概要
+ +

總覽

+ +

在定義了模型並創建了一些可以使用的初始庫記錄之後,是時候編寫將這些信息呈現給用戶的代碼了。 我們要做的第一件事是確定我們要在頁面中顯示的信息,並定義用於返回這些資源的URL。 然後,我們將創建一個URL映射器,視圖和模板來顯示頁面。

+ +

下圖描述了主要數據流,以及處理HTTP請求和響應時所需的組件。 當我們已經實現了模型時,我們將創建的主要組件是:

+ + + +

+ +

正如您將在下一節中看到的那樣,我們將顯示5頁,這是太多信息,無法在一篇文章中進行記錄。 因此,本文將重點介紹如何實現主頁,我們將在後續文章中介紹其他頁面。 這應該使您對URL映射器,視圖和模型在實踐中如何工作有很好的端到端理解。

+ +

定義資源URL

+ +

由於此版本的LocalLibrary對於最終用戶基本上是只讀的,因此我們只需要提供該網站的登錄頁面(主頁),以及顯示書籍和作者的列表和詳細視圖的頁面。

+ +

我們頁面所需的URL是:

+ + + +

前三個URL用於列出索引,書籍和作者。 它們不對任何其他信息進行編碼,並且雖然返回的結果將取決於數據庫中的內容,但為獲取信息而運行的查詢將始終相同。

+ +

相比之下,最後兩個URL用於顯示有關特定書籍或作者的詳細信息-這些URL編碼要顯示在URL中的項目的標識(如上顯示為<id>)。 URL映射器可以提取編碼信息並將其傳遞給視圖,然後將動態確定從數據庫中獲取哪些信息。 通過在我們的URL中編碼信息,我們只需要一個URL映射,視圖和模板即可處理每本書(或作者)。

+ +
+

注意: Django允許您以自己喜歡的任何方式來構造URL-您可以如上所示在URL主體中編碼信息或使用URL GET 參數(例如/book/?id=6)。 無論使用哪種方法,都應保持URL的整潔,邏輯和可讀性(在此處查看W3C建議).

+ +

Django文檔傾向於建議在URL正文中編碼信息,他們認為這種做法鼓勵更好的URL設計。

+
+ +

如概述中所述,本文的其餘部分描述瞭如何構造索引頁。

+ +

創建索引頁面

+ +

我們將創建的第一頁是索引頁 (catalog/)。 這將顯示一些靜態HTML,以及數據庫中不同記錄的一些計算出的“計數”。 為了完成這項工作,我們必須創建一個URL映射,視圖和模板。

+ +
+

注意:值得在本節中多加註意。 大多數材料是所有頁面共有的。

+
+ +

URL mapping

+ +

創建skeleton website 時,我們更新了locallibrary/urls.py文件,以確保每當收到以 catalog/  開頭的URL時, URLConf 模組 catalog.urls 都將處理其餘的子字符串。

+ +

來自 locallibrary/urls.py的以下代碼片段包括catalog.urls 模塊:

+ +
urlpatterns += [
+    path('catalog/', include('catalog.urls')),
+]
+
+ +
+

注意: 每當Django遇到導入函數 django.urls.include()時,它都會在指定的結束字符處分割URL字符串,並將剩餘的子字符串發送到所包含的URLconf 模塊以進行進一步處理。

+
+ +

我們還為URLConf 模塊創建了一個佔位符文件,名為 /catalog/urls.py。 將以下行添加到該文件:

+ +
urlpatterns = [
+    path('', views.index, name='index'),
+]
+ +

path()函數定義以下內容:

+ + + +

path()  函數還指定一個name參數,它是此特定URL映射的唯一標識符。 您可以使用該名稱來“反向”映射器,即,動態創建指向映射器旨在處理的資源的URL。 例如,通過在模板中添加以下鏈接,我們可以使用name參數從任何其他頁面鏈接到我們的主頁:

+ +
<a href="{% url 'index' %}">Home</a>.
+ +
+

注意: 我們可以對上面的鏈接進行硬編碼 (例如<a href="/catalog/">Home</a>), 但是如果我們更改主頁的模式 (例如更改為 /catalog/index) 則模板將不再 正確鏈接。 使用反向URL映射更加靈活和健壯!

+
+ +

View (function-based)

+ +

View是一個用來處理 HTTP 請求的函式,根據需求從資料庫取得資料,通過使用 HTML 模板呈現此數據來生成 HTML , 並且在一個 HTTP 回應中返回 HTML 來呈現給用戶。Index view 遵循這個模型 — 獲取有關數據庫中有多少 Book, BookInstance, 可用的 BookInstance 還有 Author 的訊息, 然後把他們傳遞給模板進行顯示。

+ +

打開catalog/views.py, 並且注意該文件已經導入 render() 快捷功能已使用模板和數據生成HTML文件。 

+ +
from django.shortcuts import render
+
+# Create your views here.
+
+ +

將以下代碼複製到文件底部。 第一行導入將用於訪問所有視圖中的數據的模型類。

+ +
from .models import Book, Author, BookInstance, Genre
+
+def index(request):
+    """View function for home page of site."""
+
+    # Generate counts of some of the main objects
+    num_books = Book.objects.all().count()
+    num_instances = BookInstance.objects.all().count()
+
+    # Available books (status = 'a')
+    num_instances_available = BookInstance.objects.filter(status__exact='a').count()
+
+    # The 'all()' is implied by default.
+    num_authors = Author.objects.count()
+
+    context = {
+        'num_books': num_books,
+        'num_instances': num_instances,
+        'num_instances_available': num_instances_available,
+        'num_authors': num_authors,
+    }
+
+    # Render the HTML template index.html with the data in the context variable
+    return render(request, 'index.html', context=context)
+ +

視圖函數的第一部分使用模型類上的 objects.all() 屬性獲取記錄數。 它還獲取具有狀態字段值為“ a”(可用)的BookInstance 物件列表。 在上一教程(Django Tutorial Part 3: Using models > Searching for records)中,您可以找到更多有關如何從模型進行訪問的信息。.

+ +

在函數的最後,我們調用 render() 函數來創建並返回HTML頁面作為響應(此快捷功能包裝了許多其他函數,從而簡化了這種非常常見的用例)。它以原始 request 物件 (一個 HttpRequest), 帶有數據佔位符的HTML模板以及上下文 context 變量包含將插入到這些佔位符中的數據的Python字典)為參數。

+ +

在下一節中,我們將詳細討論模板和上下文變量。 讓我們開始創建模板,以便實際上可以向用戶顯示內容!

+ +

Template

+ +

模板是一個文本文件,用於定義文件(例如HTML頁面)的結構或佈局,並使用佔位符表示實際內容。 Django會在您的應用程序名為'templates'的目錄中自動查找模板。 因此,例如,在我們剛剛添加的索引視圖中, render() 函數將有望能夠找到文件 /locallibrary/catalog/templates/index.html,如果找不到該文件,則會引發錯誤。 如果您保存以前的更改並返回瀏覽器,則可以看到此信息-訪問127.0.0.1:8000現在將為您提供一個相當直觀的錯誤消息"TemplateDoesNotExist at /catalog/"以及其他詳細信息。

+ +
+

注意: Django將根據項目的設置文件在許多位置查找模板(搜索已安裝的應用程序是默認設置!)。 您可以在 Templates (Django docs)中找到有關Django如何查找模板及其支持的模板格式的更多信息。

+
+ +

Extending templates

+ +

索引模板的頭部和身體將需要標準的HTML標記,以及用於導航的部分(到我們尚未創建的站點中的其他頁面)以及用於顯示一些介紹性文本和我們的書籍數據的部分。 對於我們網站上的每個頁面,大部分文本(HTML和導航結構)都是相同的。 Django模板語言允許您聲明一個基本模板,然後擴展它,而不是強迫開發人員在每個頁面中都複製此"樣板" ,只需替換每個特定頁面上不同的部分即可。

+ +

例如,基本模板 base_generic.html 可能類似於以下文本。 如您所見,其中包含一些"通用" HTML以及標題,側邊欄和內容的部分,這些部分使用命名的blockendblock 模板標記進行了標記(以粗體顯示)。 區塊可以為空,或包含將在默認情況下用於派生頁面的內容。

+ +
+

注意:模板tags 類似於可以在模板中使用的功能,可以在模板中循環使用列表,基於變量的值執行條件操作等。除了模板標記之外,模板語法還允許您引用模板變量(傳遞給 模板),並使用template filters,該過濾器可重新格式化變量(例如,將字符串設置為小寫)。

+
+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+  {% block title %}<title>Local Library</title>{% endblock %}
+</head>
+
+<body>
+  {% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %}
+  {% block content %}<!-- default content text (typically empty) -->{% endblock %}
+</body>
+</html>
+
+ +

當我們想為特定視圖定義模板時,我們首先指定基本模板(帶有extends 模板標籤-請參見下一個代碼清單)。 如果我們要在模板中替換任何節,則使用與基本模板中相同的block/endblock節來聲明這些節。

+ +

例如,下面的代碼片段顯示了我們如何使用extends 模板標籤並覆蓋content 區塊。 生成的最終HTML將具有基本模板中定義的所有HTML和結構(包括您在title 區塊中定義的默認內容),但是將新的content 區塊插入到默認模板中。

+ +
{% extends "base_generic.html" %}
+
+{% block content %}
+  <h1>Local Library Home</h1>
+  <p>Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>!</p>
+{% endblock %}
+ +

The LocalLibrary base template

+ +

下面列出了我們計劃用於LocalLibrary 網站的基本模板。 如您所見,其中包含一些HTML以及 title, sidebar, 和 content。 我們有一個默認標題(我們可能想要更改)和一個默認側邊欄,其中帶有指向所有書籍和作者列表的鏈接(我們可能不想更改,但是如果需要的話,我們允許範圍通過將其放在 在一個區塊中)。

+ +
+

注意: 我們還引入了兩個附加的模板標籤:urlload static。 這些將在以下各節中討論。

+
+ +

創建一個新文件/locallibrary/catalog/templates/base_generic.html ,並為其提供以下內容:

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+  {% block title %}<title>Local Library</title>{% endblock %}
+  <meta charset="utf-8">
+  <meta name="viewport" content="width=device-width, initial-scale=1">
+  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
+
+  <!-- Add additional CSS in static file -->
+  {% load static %}
+  <link rel="stylesheet" href="{% static 'css/styles.css' %}">
+</head>
+<body>
+  <div class="container-fluid">
+    <div class="row">
+      <div class="col-sm-2">
+      {% block sidebar %}
+      <ul class="sidebar-nav">
+        <li><a href="{% url 'index' %}">Home</a></li>
+        <li><a href="">All books</a></li>
+        <li><a href="">All authors</a></li>
+      </ul>
+     {% endblock %}
+      </div>
+      <div class="col-sm-10 ">
+      {% block content %}{% endblock %}
+      </div>
+    </div>
+  </div>
+</body>
+</html>
+ +

該模板包括來自Bootstrap的CSS,以改進HTML頁面的佈局和表示方式。 使用Bootstrap或其他客戶端Web框架是創建吸引人的頁面的快速方法,該頁面可以在不同的瀏覽器大小上很好地擴展。

+ +

基本模板還引用了本地CSS文件 (styles.css) ,該文件提供了一些其他樣式。 創建 /locallibrary/catalog/static/css/styles.css並為其提供以下內容:

+ +
.sidebar-nav {
+    margin-top: 20px;
+    padding: 0;
+    list-style: none;
+}
+ +

The index template

+ +

創建HTML文件 /locallibrary/catalog/templates/index.html 並為其提供以下內容。 如您所見,我們在第一行中擴展了基本模板,然後使用該模板的新內容塊替換默認content 區塊。

+ +
{% extends "base_generic.html" %}
+
+{% block content %}
+  <h1>Local Library Home</h1>
+  <p>Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>!</p>
+
+  <h2>Dynamic content</h2>
+  <p>The library has the following record counts:</p>
+  <ul>
+    <li><strong>Books:</strong> \{{ num_books }}</li>
+    <li><strong>Copies:</strong> \{{ num_instances }}</li>
+    <li><strong>Copies available:</strong> \{{ num_instances_available }}</li>
+    <li><strong>Authors:</strong> \{{ num_authors }}</li>
+  </ul>
+{% endblock %}
+ +

Dynamic content 部分中,我們聲明了要從視圖中包含的信息的佔位符(template variables)。 變量使用“雙括號”或“把手”語法標記(請參見上面的粗體)。

+ +
+

注意:因為變量具有雙括號 (\{{ num_books }}),而標籤則用百分號括在單括號中擴展為 ({% extends "base_generic.html" %}),所以您可以輕鬆識別是要處理模板變量還是模板標籤(函數)。

+
+ +

這裡要注意的重要一點是,這些變量是使用我們在視圖的render() 函數中傳遞給context 字典的鍵命名的(請參見下文); 呈現模板時,這些將被其values 替換。

+ +
context = {
+    'num_books': num_books,
+    'num_instances': num_instances,
+    'num_instances_available': num_instances_available,
+    'num_authors': num_authors,
+}
+
+return render(request, 'index.html', context=context)
+ +

Referencing static files in templates

+ +

您的項目可能會使用靜態資源,包括JavaScript,CSS和圖像。 由於這些文件的位置可能未知(或可能會更改),因此Django允許您相對於STATIC_URL 全局設置在模板中指定這些文件的位置(默認框架網站將STATIC_URL 的值設置為'/static/',但您可以選擇將其託管在內容分發網絡或其他地方)。

+ +

在模板中,您首先調用指定為“ static”的load 模板標籤以添加此模板庫(如下所示)。 加載靜態文件後,您可以使用static 模板標籤,指定感興趣文件的相對URL。

+ +
<!-- Add additional CSS in static file -->
+{% load static %}
+<link rel="stylesheet" href="{% static 'css/styles.css' %}">
+ +

如果需要,您可以以相同的方式將圖像添加到頁面中。 例如:

+ +
{% load static %}
+<img src="{% static 'catalog/images/local_library_model_uml.png' %}" alt="UML diagram" style="width:555px;height:540px;">
+
+ +
+

注意:上面的更改指定了文件的位置,但是Django默認不提供文件。創建網站框架時 (created the website skeleton),雖然我們在全局URL映射器(/locallibrary/locallibrary/urls.py)中啟用了由開發Web服務器提供的服務,但您仍需要安排它們在生產中提供。 我們待會再看。

+
+ +

有關使用靜態文件的更多信息,請參閱管理靜態文件 Managing static files (Django docs)。

+ +

Linking to URLs

+ +

上面的基本模板引入了url 模板標籤。

+ +
<li><a href="{% url 'index' %}">Home</a></li>
+
+ +

此標記採用在 urls.py中調用的 path()函數的名稱以及關聯視圖將從該函數接收的任何參數的值,並返回可用於鏈接到資源的URL。

+ +

What does it look like?

+ +

此時,我們應該已經創建了顯示索引頁面所需的所有內容。 運行服務器(python3 manage.py runserver),然後打開瀏覽器到http://127.0.0.1:8000/。 如果一切設置正確,則您的站點應類似於以下螢幕截圖。

+ +

Index page for LocalLibrary website

+ +
+

注意:您將無法使用All booksAll authors鏈接,因為尚未定義這些頁面的路徑,視圖和模板(當前我們僅在base_generic.html html模板中插入了這些鏈接的佔位符)。

+
+ +

Challenge yourself

+ +

這裡有兩個任務可以測試您對模型查詢,視圖和模板的熟悉程度。

+ +
    +
  1. LocalLibrary base template 已定義title 欄。 在 index template中覆蓋此塊並為頁面創建一些新標題。 + +
    +

    提示 :Extending templates 部分介紹瞭如何創建塊並將其擴展到另一個模板中。
    +  

    +
    +
  2. +
  3. 修改 view以生成包含特定單詞(不區分大小寫)的流派計數和書籍計數,並將其傳遞給context (這與我們創建並使用num_booksnum_instances_available的方式大致相同)。 然後更新 index template 以使用這些變量。
  4. +
+ + + +

Summary

+ +

現在,我們已經為網站創建了主頁-一個HTML頁面,該頁面顯示了數據庫中的一些記錄計數,並具有指向其他尚待創建頁面的鏈接。 在此過程中,我們學習了很多有關url映射器,視圖,使用我們的模型查詢數據庫,如何從視圖中將信息傳遞到模板以及如何創建和擴展模板的基本信息。

+ +

在下一篇文章中,我們將基於我們的知識來創建其他四個頁面。

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/Server-side/Django/Admin_site", "Learn/Server-side/Django/Generic_views", "Learn/Server-side/Django")}}

+ +

In this module

+ + diff --git a/files/zh-tw/learn/server-side/django/index.html b/files/zh-tw/learn/server-side/django/index.html new file mode 100644 index 0000000000..7bb4840e06 --- /dev/null +++ b/files/zh-tw/learn/server-side/django/index.html @@ -0,0 +1,115 @@ +--- +title: Django 網站框架 (Python) +slug: Learn/Server-side/Django +translation_of: Learn/Server-side/Django +--- +
{{LearnSidebar}}
+ +

Django 使用 Python 語言編寫,是一個廣受歡迎、且功能完整的服務器端網站框架。本模塊將為您展示,為什麼 Django 能夠成為一個廣受歡迎的服務器端框架,如何設置開發環境,以及如何開始創建你自己的網絡應用。

+ +

先決條件

+ +

開始學習本模塊,並不需要任何 Django 知識. 但您要理解什麼是服務器端網絡編程、什麼是網絡框架,最好能夠閱讀我們的服務端網站編程的第一步模塊

+ +

最好能有基本的編程概念、並了解 Python 語言,但並不是理解本教程的核心概念的必然條件。

+ +
+

Note: 對於初學者來說,Python 是最容易閱讀和理解的編程語言之一。也就是說,如果您想更好的理解本教程,網上有很多免費書籍及免費教程可供參考學習(建議初學者查看 Python 官網的 Python for Non Programmers )。

+
+ +

指引

+ +
+
Django 簡介
+
在第一篇關於 Django 的文章裡,我們會回答"什麼是Django?",並概述這個網絡框架的特殊之處。我們會列出主要的功能,包括一些高級的功能特性,這些高級特性我們在這部分教程裡沒有時間詳細說明。在你設置好 Django 應用、並開始把玩它之前,我們會展示 Django 應用的一些主要模塊,讓你明白 Django 應用能做什麼。  
+
架設 Django 開發環境
+
現在你知道 Django 是做什麼的,我們會展示怎樣在 Windows、Linux(Ubuntu)、和 Mac OS X上,創建和測試 Django 的開發環境—不管你是用什麼操作系統,這篇文章會教給你能夠開發 Django 應用所需要的開發環境。
+
Django 教學 1: 本地圖書館網站
+
我們實用教程系列的第一篇文章,會解釋你將學習到什麼,並提供 "本地圖書館" 網站這個例子的概述。我們會在接下來的文章裡,完成並不斷的改進這個網站。
+
Django 教學 2: 創建骨架網站
+
這篇文章會教你,怎樣創建一個網站的 "框架" 。以這個網站為基礎,你可以填充網站特定的 settings、urls、models、views 和 templates。
+
Django 教學 3: 使用模型
+
這篇文章會為 “本地圖書館網站” 定義數據模板—數據模板是我們為應用存儲的數據結構。並且允許 Django 在資料庫中存儲數據(以後可以修改)。此文章解釋了什麼是數據模板、怎樣聲明它、和一些主要的數據種類。文章還簡要的介紹了一些,你可以獲得數據模板的方法。
+
Django 教學 4: Django 管理員頁面
+
現在我們已經為本地圖書館網站,創建了模型,我們將使用 Django 管理員頁面添加一些 ‘真實的’ 的圖書數據。首先,我們將向你介紹,如何使用管理員頁面註冊模型,然後我們介紹如何登錄和創建一些數據。最後我們展示一些,進一步改進管理員頁面呈現的方法。
+
Django 教學 5: 創建我們的首頁
+
我們現在可以添加代碼,來展示我們的第一個完整頁面—本地圖書館主頁,來顯示我們對每個模型類型有多少條記錄,並提供我們其他頁面的側邊欄導航鏈接。一路上,我們將獲得編寫基本 URL 地圖和視圖、從數據庫獲取記錄、以及使用模版的實踐經驗。.
+
Django 教學 6: 通用列表與詳細視圖
+
本教學課程擴展了我們的本地圖書館網站,添加書籍和作者和詳細頁面。在這裡,我們將了解基於類別的通用視圖,並展示如何減少常用代碼用例的代碼量。我們還將更詳細地深入理解 URL 處理,展示如何執行基本模式匹配。   
+
Django 教學 7: 會話框架
+
本教學擴展本地圖書館網站,向首頁添加了一個基於會話的訪問計數器。這是個比較簡單的例子,但它顯示如何使用會話框架,為你自己的網站中的匿名用戶,提供一致的行為。
+
Django 教學 8: 使用者身份驗証和權限
+
本教程,我們將向你展示,如何允許使用者用自己的賬戶,登錄到你的網站,以及如何根據他們是否登錄、及其權限,來控制他們可以做什麼、和看到什麼。作為此次演示的一部分,我們將擴展本地圖書館網站,添加登錄和登出頁面,以及使用者和工作人員特定頁面,以查看已借用的書籍。
+
Django 教學 9: 使用表單
+
本教程,我們將向你展示如何使用 Django 中的 HTML Forms 表單,特別是編寫表單以創建、更新、和刪除模型實例的最簡單方法。作為此次演示的一部分,我們將擴展本地圖書館網站,以便圖書館員,可以使用我們自己的表單 (而不是使用管理應用程序) 來更新書籍,創建、更新、刪除作者。
+
Django 教學 10: 測試 Django 網頁應用
+
隨著網站的的發展,手工測試越來越難測試—不僅要測試更多,而且隨著組件之間的相互作用變得越來越複雜,一個領域的一個小的變化,可能需要許多額外的測試,來驗證其對其他領域的影響。減輕這些問題的一種方法,是編寫自動化測試,每次更改時,都可以輕鬆可靠地運行。本教程將介紹如何使用 Django 的測試框架,對你的網站進行單元測試自動化。
+
Django 教學 11: 部署 Django 到生產環境
+
現在,你已創建(並測試)一個很酷的 “本地圖書館網站”,你將要把它安裝在公共 Web 服務器上,以便圖書館員工和成員,可以通過 Internet 訪問。本文概述如何找到主機,來部署你的網站,以及你需要做什麼,才能使你的網站準備好投入生產環境。
+
Django 網頁應用安全
+
保護用戶數據,是任何網站設計的重要組成部分,我們以前解釋了Web 安全文章中,一些更常見的安全威脅—本文提供了 Django 內置、如何保護處理這種危險的實際演示。
+
+ +

評估

+ +

以下評估,將測試你對如何使用 Django 創建網站的理解,如上述指南中所列出的項目。

+ +
+
DIY Django 微博客
+
在這個評估中,你將使用你從本單元中學到的一些知識,來創建自己的博客。
+
+
{{LearnSidebar}}
+ +

Django 使用 Python 語言編寫,是一個廣受歡迎、且功能完整的服務器端網站框架。本模塊將為您展示,為什麼 Django 能夠成為一個廣受歡迎的服務器端框架,如何設置開發環境,以及如何開始創建你自己的網絡應用。

+ +

先決條件

+ +

開始學習本模塊,並不需要任何 Django 知識. 但您要理解什麼是服務器端網絡編程、什麼是網絡框架,最好能夠閱讀我們的服務端網站編程的第一步模塊

+ +

最好能有基本的編程概念、並了解 Python 語言,但並不是理解本教程的核心概念的必然條件。

+ +
+

Note: 對於初學者來說,Python 是最容易閱讀和理解的編程語言之一。也就是說,如果您想更好的理解本教程,網上有很多免費書籍及免費教程可供參考學習(建議初學者查看 Python 官網的 Python for Non Programmers )。

+
+ +

指引

+ +
+
Django 簡介
+
在第一篇關於 Django 的文章裡,我們會回答"什麼是Django?",並概述這個網絡框架的特殊之處。我們會列出主要的功能,包括一些高級的功能特性,這些高級特性我們在這部分教程裡沒有時間詳細說明。在你設置好 Django 應用、並開始把玩它之前,我們會展示 Django 應用的一些主要模塊,讓你明白 Django 應用能做什麼。  
+
架設 Django 開發環境
+
現在你知道 Django 是做什麼的,我們會展示怎樣在 Windows、Linux(Ubuntu)、和 Mac OS X上,創建和測試 Django 的開發環境—不管你是用什麼操作系統,這篇文章會教給你能夠開發 Django 應用所需要的開發環境。
+
Django 教學 1: 本地圖書館網站
+
我們實用教程系列的第一篇文章,會解釋你將學習到什麼,並提供 "本地圖書館" 網站這個例子的概述。我們會在接下來的文章裡,完成並不斷的改進這個網站。
+
Django 教學 2: 創建骨架網站
+
這篇文章會教你,怎樣創建一個網站的 "框架" 。以這個網站為基礎,你可以填充網站特定的 settings、urls、models、views 和 templates。
+
Django 教學 3: 使用模型
+
這篇文章會為 “本地圖書館網站” 定義數據模板—數據模板是我們為應用存儲的數據結構。並且允許 Django 在資料庫中存儲數據(以後可以修改)。此文章解釋了什麼是數據模板、怎樣聲明它、和一些主要的數據種類。文章還簡要的介紹了一些,你可以獲得數據模板的方法。
+
Django 教學 4: Django 管理員頁面
+
現在我們已經為本地圖書館網站,創建了模型,我們將使用 Django 管理員頁面添加一些 ‘真實的’ 的圖書數據。首先,我們將向你介紹,如何使用管理員頁面註冊模型,然後我們介紹如何登錄和創建一些數據。最後我們展示一些,進一步改進管理員頁面呈現的方法。
+
Django 教學 5: 創建我們的首頁
+
我們現在可以添加代碼,來展示我們的第一個完整頁面—本地圖書館主頁,來顯示我們對每個模型類型有多少條記錄,並提供我們其他頁面的側邊欄導航鏈接。一路上,我們將獲得編寫基本 URL 地圖和視圖、從數據庫獲取記錄、以及使用模版的實踐經驗。.
+
Django 教學 6: 通用列表與詳細視圖
+
本教學課程擴展了我們的本地圖書館網站,添加書籍和作者和詳細頁面。在這裡,我們將了解基於類別的通用視圖,並展示如何減少常用代碼用例的代碼量。我們還將更詳細地深入理解 URL 處理,展示如何執行基本模式匹配。   
+
Django 教學 7: 會話框架
+
本教學擴展本地圖書館網站,向首頁添加了一個基於會話的訪問計數器。這是個比較簡單的例子,但它顯示如何使用會話框架,為你自己的網站中的匿名用戶,提供一致的行為。
+
Django 教學 8: 使用者身份驗証和權限
+
本教程,我們將向你展示,如何允許使用者用自己的賬戶,登錄到你的網站,以及如何根據他們是否登錄、及其權限,來控制他們可以做什麼、和看到什麼。作為此次演示的一部分,我們將擴展本地圖書館網站,添加登錄和登出頁面,以及使用者和工作人員特定頁面,以查看已借用的書籍。
+
Django 教學 9: 使用表單
+
本教程,我們將向你展示如何使用 Django 中的 HTML Forms 表單,特別是編寫表單以創建、更新、和刪除模型實例的最簡單方法。作為此次演示的一部分,我們將擴展本地圖書館網站,以便圖書館員,可以使用我們自己的表單 (而不是使用管理應用程序) 來更新書籍,創建、更新、刪除作者。
+
Django 教學 10: 測試 Django 網頁應用
+
隨著網站的的發展,手工測試越來越難測試—不僅要測試更多,而且隨著組件之間的相互作用變得越來越複雜,一個領域的一個小的變化,可能需要許多額外的測試,來驗證其對其他領域的影響。減輕這些問題的一種方法,是編寫自動化測試,每次更改時,都可以輕鬆可靠地運行。本教程將介紹如何使用 Django 的測試框架,對你的網站進行單元測試自動化。
+
Django 教學 11: 部署 Django 到生產環境
+
現在,你已創建(並測試)一個很酷的 “本地圖書館網站”,你將要把它安裝在公共 Web 服務器上,以便圖書館員工和成員,可以通過 Internet 訪問。本文概述如何找到主機,來部署你的網站,以及你需要做什麼,才能使你的網站準備好投入生產環境。
+
Django 網頁應用安全
+
保護用戶數據,是任何網站設計的重要組成部分,我們以前解釋了 Web 安全文章中,一些更常見的安全威脅—本文提供了 Django 內置、如何保護處理這種危險的實際演示。
+
+ +

評估

+ +

以下評估,將測試你對如何使用 Django 創建網站的理解,如上述指南中所列出的項目。

+ +
+
Django 小部落格 DIY
+
在這個評估中,你將使用你從本單元中學到的一些知識,來創建自己的部落格。
+
diff --git a/files/zh-tw/learn/server-side/django/introduction/index.html b/files/zh-tw/learn/server-side/django/introduction/index.html new file mode 100644 index 0000000000..f0a9e2caa5 --- /dev/null +++ b/files/zh-tw/learn/server-side/django/introduction/index.html @@ -0,0 +1,306 @@ +--- +title: Django 介紹 +slug: Learn/Server-side/Django/Introduction +translation_of: Learn/Server-side/Django/Introduction +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/Server-side/Django/development_environment", "Learn/Server-side/Django")}}
+ +

在這第一篇Django文章中,我們將回答“什麼是Django”這個問題,並概述這個網絡框架有什麼特性。我們將描述主要功能,包括一些高級功能,但我們並不會在本單元中詳細介紹。我們還會展示一些Django應用程序的主要構建模塊(儘管此時你還沒有要測試的開發環境)。

+ + + + + + + + + + + + +
先備知識:基本的電腦知識.對服務器端網站編程的一般了解 ,特別是網站中客戶端-服務器交互的機制 .
目標:了解Django是什麼,它提供了哪些功能,以及Django應用程序的主要構建塊。
+ +

什麼是 Django?

+ +

Django 是一個高級的 Python 網路框架,可以快速開發安全和可維護的網站。由經驗豐富的開發者構建,Django 負責處理網站開發中麻煩的部分,因此你可以專注於編寫應用程序,而無需重新開發。

+ +

它是免費和開源的,有活躍繁榮的社區、豐富的文檔、以及很多免費和付費的解決方案。

+ +

Django 可以使你的應用具有以下優點:

+ +
+
完備
+
Django 遵循 “功能完備” 的理念,提供開發人員可能想要 “開箱即用” 的幾乎所有功能。因為你需要的一切,都是一個 ”產品“ 的一部分,它們都可以無縫結合在一起,遵循一致性設計原則,並且具有廣泛、和最新的文檔
+
通用
+
+

Django 可以(並已經)用於構建幾乎任何類型的網站—從內容管理系統和維基,到社交網絡和新聞網站。它可以與任何客戶端框架一起工作,並且可以提供幾乎任何格式(包括 HTML、RSS、JSON、XML等)的內容。你正在閱讀的網站就是基於 Django。

+ +

在內部,儘管它為幾乎所有可能需要的功能(例如幾個流行的資料庫,模版引擎等)提供了選擇,但是如果需要,它也可以擴展到使用其他組件。

+
+
安全
+
+

Django 幫助開發人員,通過提供一個被設計為 “做正確的事情” 來自動保護網站的框架,來避免許多常見的安全錯誤。例如,Django 提供了一種安全的方式,來管理用戶帳號和密碼,避免了常見的錯誤,比如將 session 放在 cookie 中這種易受攻擊的做法(取而代之的是,cookies 只包含一個密鑰,實際數據存儲在數據庫中),或直接存儲密碼,而不是密碼的 hash 值。

+ +

密碼 hash ,是讓密碼通過加密 hash 函數,而創建的固定長度值。 Django 能通過運行 hash 函數,來檢查輸入的密碼 - 就是將輸出的 hash 值,與存儲的 hash 值進行比較是否正確。然而由於功能的 “單向” 性質,假使存儲的 hash 值受到威脅,攻擊者也難以解出原始密碼。 (但其實有彩虹表-譯者觀點)

+ +

默認情況下,Django 可以防範許多漏洞,包括 SQL 注入,跨站點腳本,跨站點請求偽造,和點擊劫持 (請參閱 網站安全 相關信息,如有興趣)。

+
+
可擴展
+
Django 使用基於組件的 “無共享” 架構 (架構的每一部分獨立於其他架構,因此可以根據需要進行替換或更改)。在不同部分之間,有明確的分隔,意味著它可以通過在任何級別添加硬件,來擴展服務:緩存服務器,數據庫服務器,或應用程序服務器。一些最繁忙的網站,已經在 Django 架構下成功地縮放了網站的規模大小,以滿足他們的需求(例如 Instagram 和 Disqus,僅舉兩個例子,可自行添加)。
+
可維護
+
Django 代碼編寫,是遵照設計原則和模式,鼓勵創建可維護和可重複使用的代碼。特別是,它使用了不要重複自己(DRY)原則,所以沒有不必要的重複,減少了代碼的數量。 Django 還將相關功能,分組到可重用的 “應用程序” 中,並且在較低級別,將相關代碼分組或模塊( 模型視圖控制器 Model View Controller (MVC) 模式)。
+
可移植
+
Django 是用 Python 編寫的,它在許多平台上運行。這意味著,你不受任務特定的服務器平台的限制,並且可以在許多種類的 Linux,Windows 和 Mac OS X 上運行應用程序。此外,Django 得到許多網路託管提供商的好評,他們經常提供特定的基礎設施,和託管 Django 網站的文檔。
+
+ +

Django的起源?

+ +

Django 最初在 2003 年到 2005 年間,由負責創建和維護報紙網站的網絡團隊開發。在創建了許多網站後,團隊開始考慮、並重用許多常見的代碼和設計模式。這個共同的代碼,演變一個通用的網絡開發框架,2005 年 7 月,被開源為 “Django” 項目。

+ +

Django 不斷發展壯大 — 從 2008 年 9 月的第一個里程碑版本(1.0),到最近發布的(2.0)-(2018)版本。每個版本都添加了新功能,和錯誤修復,從支持新類型的數據庫,模版引擎和緩存,到添加 “通用” 視圖函數和類別(這減少了開發人員在一些編程任務必須編寫的代碼量)。

+ +
+

注意: 查看 Django 網站上的發行說明 release notes,看看最近版本發生了什麼變化,以及 Django 能做多少工作

+
+ +

Django 現在是一個蓬勃發展的合作開源項目,擁有數千個用戶和貢獻者。雖然它仍然具有反映其起源的一些功能,但 Django 已經發展成為,能夠開發任何類型的網站的多功能框架。

+ +

Django有多受歡迎?

+ +

服務器端框架的受歡迎程度沒有任何可靠和明確的測量(儘管Hot Frameworks網站嘗試使用諸如計算每個平台的GitHub項目數量和StackOverflow問題的機制來評估流行度)。一個更好的問題是Django是否“足夠流行”,以避免不受歡迎的平台的問題。它是否繼續發展?如果您需要幫助,可以幫您嗎?如果您學習Django,有機會獲得付費工作嗎?

+ +

基於使用Django的流行網站數量,為代碼庫貢獻的人數以及提供免費和付費支持的人數,那麼是的,Django是一個流行的框架!

+ +

使用Django的流行網站包括:Disqus,Instagram,騎士基金會,麥克阿瑟基金會,Mozilla,國家地理,開放知識基金會,Pinterest和開放棧(來源:Django home page ).

+ +

Django 是特定用途的?

+ +

Web框架通常將自己稱為“特定”或“無限制”。

+ +

特定框架是對處理任何特定任務的“正確方法”有意見的框架。他們經常支持特定領域的快速發展(解決特定類型的問題),因為正確的做法是通常被很好地理解和記錄在案。然而,他們在解決其主要領域之外的問題時可能不那麼靈活,並且傾向於為可以使用哪些組件和方法提供較少的選擇。

+ +

相比之下,无限制的框架对于将组件粘合在一起以实现目标或甚至应使用哪些组件的最佳方式的限制较少。它们使开发人员更容易使用最合适的工具来完成特定任务,尽管您需要自己查找这些组件。

+ +

Django“有點有意義”,因此提供了“兩個世界的最佳”。它提供了一組組件來處理大多數Web開發任務和一個(或兩個)首選的使用方法。然而,Django的解耦架構意味著您通常可以從多個不同的選項中進行選擇,也可以根據需要添加對全新的支持。

+ +

Django 代碼是什麼樣子?

+ +

在傳統的數據驅動網站中,Web應用程序會等待來自Web瀏覽器(或其他客戶端)的HTTP 請求。當接收到請求時,應用程序根據URL 和可能的POST 數據或GET 數據中的信息確定需要的內容。根據需要,可以從數據庫讀取或寫入信息,或執行滿足請求所需的其他任務。然後,該應用程序將返回對Web瀏覽器的響應,通常通過將檢索到的數據插入HTML模板中的佔位符來動態創建用於瀏覽器顯示的HTML 頁面。

+ +

Django 網絡應用程序通常將處理每個步驟的代碼分組到單獨的文件中:

+ +

+ + + +
+

注意 : Django將此組織稱為“模型視圖模板(MVT)”架構。它與更加熟悉的Model View Controller架構有許多相似之處.

+
+ + + +

以下部分將為您提供Django應用程序的這些主要部分的想法(稍後我們將在進一步詳細介紹後,我們將在開發環境中進行更詳細的介紹)。

+ +

將請求發送到正確的視圖(urls.py)

+ +

URL映射器通常存儲在名為urls.py的文件中。在下面的示例中,mapper(urlpatterns)定義了特定URL 模式和相應視圖函數之間的映射列表。如果接收到具有與指定模式匹配的URL(例如r'^$',下面)的HTTP請求,則將調用相關聯的視圖功能(例如 views.index)並傳遞請求。

+ +
urlpatterns = [
+    path('admin/', admin.site.urls),
+    path('book/<int:id>/', views.book_detail, name='book_detail'),
+    path('catalog/', include('catalog.urls')),
+    re_path(r'^([0-9]+)/$', views.best),
+]
+
+ +

urlpatterns對像是path()和/或re_path()函數的列表(Python列表使用方括號定義,其中項目用逗號分隔,可以有一個可選的尾隨逗號。例如:[item1, item2, item3, ])。

+ +

兩種方法的第一個參數,是將要匹配的路由(模式)。 path()方法使用尖括號,來定義將被捕獲、並作為命名參數傳遞給視圖函數的 URL 的部分。 re_path()函數使用靈活的模式匹配方法,稱為正則表達式。我們將在後面的文章中討論這些內容!

+ +

第二個參數,是在匹配模式時將調用的另一個函數。註釋 views.book_detail表示該函數名為book_detail(),可以在名為views的模塊中找到(即在名為views.py的文件中)

+ +

處理請求(views.py)

+ + + +

視圖是Web應用程序的核心,從Web客戶端接收HTTP請求並返回HTTP響應。在兩者之間,他們編制框架的其他資源來訪問數據庫,渲染模板等。

+ +

下面的例子顯示了一個最小的視圖功能index(),這可以通過我們的URL映射器在上一節中調用。像所有視圖函數一樣,它接收一個HttpRequest對像作為參數(request)並返回一個HttpResponse對象。在這種情況下,我們對請求不做任何事情,我們的響應只是返回一個硬編碼的字符串。我們會向您顯示一個請求,在稍後的部分中會提供更有趣的內容。

+ + + +
## filename: views.py (Django view functions)
+
+from django.http import HttpResponse
+
+def index(request):
+    # Get an HttpRequest - the request parameter
+    # perform operations using information from the request.
+    # Return HttpResponse
+    return HttpResponse('Hello from Django!')
+
+ +
+

注意 :一點點Python:

+ + + + +
+ + + +

視圖通常存放在一個名為views.py的文件中。

+ +

定義數據模型(models.py)

+ + + +

Django Web應用程序,通過被稱為模型的Python對象,來管理和查詢數據。模型定義存儲數據的結構,包括字段類型 以及字段可能的最大值,默認值,選擇列表選項,文檔幫助文本,表單的標籤文本等。模型的定義與底層數據庫無關-您可以選擇其中一個,作為項目設置的一部分。一旦您選擇了要使用的數據庫,您就不需要直接與之交談- 只需編寫模型結構和其他代碼,Django可以處理與數據庫通信的所有辛苦的工作。

+ +

下面的代碼片段為Team對象,展示了一個非常簡單的Django模型。本Team類別是從Django的類別派生models.Model。它將團隊名稱和團隊級別,定義為字符字段,並為每個記錄指定了要存放的最大字符數。team_level可以是幾個值中的一個,因此,我們將其定義為一個選擇字段,並在被展示的數據、和被儲存的數據之間,建立映射,並設置一個默認值。

+ + + +
# filename: models.py
+
+from django.db import models
+
+class Team(models.Model):
+    team_name = models.CharField(max_length=40)
+
+    TEAM_LEVELS = (
+        ('U09', 'Under 09s'),
+        ('U10', 'Under 10s'),
+        ('U11', 'Under 11s'),
+        ...  #list other team levels
+    )
+    team_level = models.CharField(max_length=3,choices=TEAM_LEVELS,default='U11')
+
+ +
+

注意 : Python小知識:

+ + + + +
+ +

查詢數據(views.py)

+ + + +

Django模型提供了一個,用於搜索數據庫的簡單查詢API。這可以使用不同的標準(例如,精確,不區分大小寫,大於等等)來匹配多個字段,並且可以支持複雜語句(例如,您可以在擁有一個團隊的U11團隊上指定搜索名稱以“Fr ”開頭或以“al”結尾)。

+ +

代碼片段顯示了一個視圖函數(資源處理程序),用於顯示我們所有的U09團隊。粗體顯示如何使用模型查詢API,過濾所有記錄,其中該 team_level字段,具有正確的文本“ U09 ”(請注意,該條件如何filter()作為參數傳遞給該函數,該字段名稱和匹配類型由雙下劃線: team_level__exact

+ + + +
## filename: views.py
+
+from django.shortcuts import render
+from .models import Team
+
+def index(request):
+    list_teams = Team.objects.filter(team_level__exact="U09")
+    context = {'youngest_teams': list_teams}
+    return render(request, '/best/index.html', context)
+
+ +
+
+ +

此功能使用render ()功能創建HttpResponse發送回瀏覽器的功能。這個函數是一個快捷方式;它通過組合指定的HTML模版和一些數據來插入模版(在名為“ content ”的變量中提供)來創建一個HTML文件。在下一節中,我們將介紹如何在其中插入數據以創建HTML

+ +

呈現數據(HTML模版)

+ +

模板系統允許您使用佔位符指定輸出文檔的結構,以便在生成頁面時填充數據。模板通常用於創建HTML,但也可以創建其他類型的文檔。 Django支持其本機模板系統,和另一個流行的Python庫,名為 Jinja2(如果需要,它也可以支持其他系統)。

+ +

代碼片段,顯示了上一節中render()函數調用的HTML模板的外觀。這個模板的編寫假設它在渲染時可以訪問名為youngest_teams的列表變量(包含在上面render()函數中的上下文變量context中)。在HTML框架內部,我們有一個表達式,首先檢查youngest_teams變量是否存在,然後在for循環中迭代它。在每次迭代中,模板在{{htmlelement(“li”)}}元素中顯示每個團隊的team_name值。

+ +
## filename: best/templates/best/index.html
+
+<!DOCTYPE html>
+<html lang="en">
+<body>
+
+ {% if youngest_teams %}
+    <ul>
+    {% for team in youngest_teams %}
+        <li>\{\{ team.team_name \}\}</li>
+    {% endfor %}
+    </ul>
+{% else %}
+    <p>No teams are available.</p>
+{% endif %}
+
+</body>
+</html>
+ +

你還能做什麼?

+ + + +

前面的部分,展示了幾乎每個Web應用程序將使用的主要功能:URL映射,視圖,模型和模版。Django提供的其他內容包括:

+ + + + + +

總結

+ + + +

恭喜,您已經完成了Django之旅的第一步!您現在應該了解Django的主要優點,一些關於它的歷史,以及Django應用程序的每個主要部分可能是什麼樣子。您還應該了解Python編程語言的一些內容,包括列表,函數和類別的語法。

+ +

您已經看到上面的一些真正的Django代碼,但與客戶端代碼不同,您需要設置一個開發環境來運行它。這是我們的下一步。

+ + + +
{{NextMenu("Learn/Server-side/Django/development_environment", "Learn/Server-side/Django")}}
+ +

本教學連結

+ + diff --git a/files/zh-tw/learn/server-side/django/models/index.html b/files/zh-tw/learn/server-side/django/models/index.html new file mode 100644 index 0000000000..c075d8d35a --- /dev/null +++ b/files/zh-tw/learn/server-side/django/models/index.html @@ -0,0 +1,475 @@ +--- +title: 'Django Tutorial Part 3: Using models' +slug: Learn/Server-side/Django/Models +translation_of: Learn/Server-side/Django/Models +--- +
,{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Django/skeleton_website", "Learn/Server-side/Django/Admin_site", "Learn/Server-side/Django")}}
+ +

+ +

本文介紹如何為 LocalLibrary 網站定義模型。它解釋了模型是什麼、聲明的方式以及一些主要字段類型。它還簡要展示了您可以訪問模型數據的幾個主要方法。

+ + + + + + + + + + + + +
前提:Django 教學 2: 創建骨架網站。
目標: +

能夠設計和創建自己的模型,選擇適當的欄位。

+
+ +

概覽

+ +

Django Web 應用程序通過被稱為模型的 Python 對象,訪問和管理數據。模型定義儲存數據的結構,包括欄位類型、以及可能還有最大大小,默認值,選擇列表選項,幫助文檔,表單的標籤文本等。模型的定義與底層數據庫無關 — 你可以選擇其中一個,作為項目設置的一部分。一旦你選擇了要使用的數據庫,你就不需要直接與之交談 — 只需編寫模型結構和其他代碼,Django 可以處理與數據庫通信的所有繁瑣工作。

+ +

本教程將介紹如何定義和訪問 LocalLibrary 範例網站的模型。

+ +

設計LocalLibrary模型

+ +

在你投入開始編寫模型之前,花幾分鐘時間考慮我們需要存放的數據、以及不同物件之間的關係。

+ +

我們知道,我們需要存放書籍的信息(標題,摘要,作者,語言,類別,ISBN),並且我們可能有多個副本(具有全域唯一的ID,可用狀態等)。我們可以存放更多關於作者的信息,而不僅僅是他的名字,或多個作者的相同或相似的名稱。我們希望能根據書名,作者名,語言和類別對信息進行排序。

+ +

在設計模型時,為每個“物件”分別設置模型(相關信息分組)是有意義的。在這種情況下,明顯的物件是書籍,書本實例和作者。

+ +

你可能想要使用模型,來表示選擇列表選項(例如:選擇下拉列表),而不是硬編碼,將選項編寫進網站—這是當所有選項面臨未知、或改變時候的建議。在本網站,模型的明顯候選,包括書籍類型(例如:科幻小說,法國詩歌等)和語言(英語,法語,日語)。

+ +

一旦我們已經決定了我們的模型和字段,我們需要考慮它們的關聯性。Django允許你來定義一對一的關聯(OneToOneField),一對多(ForeignKey)和多對多(ManyToManyField)。

+ +

思考一下,在網站中,我們將定義模型展示在下面UML關聯圖中(下圖)。如以上,我們創建了書的模型(書的通用細節),書本實例(系統中特定物理副本的書籍狀態),和作者。我們也決定了各類型模型,以便通過管理界面創建/選擇值。我們決定不給BookInstance:status一個模型 —我們硬編碼了(LOAN_STATUS)的值,因為我們不希望其改變。在每個框中,你可以看到模型名稱,字段名稱和類型,以及方法和返回類型。

+ +

該圖顯示模型之間的關係,包括它們的多重性。多重性是圖中的數字,顯示可能存在於關係中的每個模型的數量(最大值和最小值)。例如,盒子之間的連接線,顯示書和類型相關。書模型中數字表明,一本書必須有一個或多個類型(想要多少就多少),而類型(Genres)模型線的另一端的數字(0..*),表明它可以有零個或多個關聯書本(可以有這個書籍類別,也有對應的書;也可以是有這個書籍類別,但沒有對應的書)。

+ +

LocalLibrary Model UML

+ +
+

注意 :下一節提供一個基本解釋模型的定義與使用,當你在讀的時候,也需要一邊考慮如何構建上圖中的每個模型。
+  

+
+ +

模型入門

+ +

本節簡要概述了模型定義,和一些重要的字段、和字段參數。

+ +

模型定義

+ +

模型通常在 app 中的 models.py 檔案中定義。它們是繼承自  django.db.models.Model的子類, 可以包括屬性,方法和描述性資料(metadata)。下面區段為一個名為MyModelName的「典型」模型範例碼:

+ +
from django.db import models
+
+class MyModelName(models.Model):
+    """A typical class defining a model, derived from the Model class."""
+
+    # Fields
+    my_field_name = models.CharField(max_length=20, help_text='Enter field documentation')
+    ...
+
+    # Metadata
+    class Meta:
+        ordering = ['-my_field_name']
+
+    # Methods
+    def get_absolute_url(self):
+         """Returns the url to access a particular instance of MyModelName."""
+         return reverse('model-detail-view', args=[str(self.id)])
+
+    def __str__(self):
+        """String for representing the MyModelName object (in Admin site etc.)."""
+        return self.field_name
+ +

在下面章節中,我們將更詳細解釋模型的每個功能。

+ +

字段

+ +

模型可以有任意數量的字段、任何類型的字段 — 每個字段都表示我們要存放在我們的一個資料庫中的一欄數據(a column of data)。每筆資料庫記錄(列 row)將由每個字段值之一組成。我們來看看上面看到的例子。

+ +
my_field_name = models.CharField(max_length=20, help_text='Enter field documentation')
+ + + +

在上面例子中,有個叫 my_field_name 的單一字段,其類型為 models.CharField  — 這意味著這個字段將會包含字母、數字字符串。使用特定的類別分配字段類型,這些類別,決定了用於將數據存放在資料庫中的記錄的類型,以及從HTML表單接收到值(即構成有效值)時使用的驗證標準。字段類型還可以獲取參數,進一步指定字段如何存放或如何被使用。在這裡的情況下,我們給了字段兩個參數:

+ + + +

字段名稱用於在視圖和模版中引用它。字段還有一個標籤,它被指定一個參數(verbose_name),或者通過大寫字段的變量名的第一個字母,並用空格替換下劃線(例如my_field_name 的默認標籤為 My field name )。

+ +

如果模型在表單中呈現(例如:在管理站點中),則聲明該字段的順序,將影響其默認順序,但可能會被覆蓋。

+ +
常用字段參數
+ +

當聲明很多/大多數不同的字段類型時,可以使用以下常用參數:

+ + + +

還有許多其他選項 — 你可以在這裡看到完整的字段選項

+ +
常用字段類型
+ +

以下列表描述了一些更常用的字段類型。

+ + + +

還有許多其他類型的字段,包括不同類型數字的字段(大整數,小整數,浮點數),布林值,URLs,唯一 ids 和其他 “時間相關” 的信息(持續時間,時間等)。你可以查閱完整列表 .

+ +

+ +

元數據(Metadata)

+ +

你可以通過宣告 class Meta 來宣告模型級別的元數據,如圖所示:

+ +
class Meta:
+    ordering = ['-my_field_name']
+
+ +

此元數據最有用的功能之一是控制在查詢模型類型時返回之記錄的默認排序。你可以透過在ordering 屬性的字段名稱列表中指定匹配順序來執行此操作,如上所示。排序將依賴字段的類型(字符串字段按字母順序排序,而日期字段按時間順序排序)。如上所示,你可以使用減號(-)前綴字段名稱以反轉排序順序。

+ +

例如,如果我們選擇依照此預設來排列書單:

+ +
ordering = ['title', '-pubdate']
+ +

書單通過標題依據--字母排序--排列,從A到Z,然後再依每個標題的出版日期,從最新到最舊排列。

+ +

另一個常見的屬性是 verbose_name ,一個 verbose_name 說明單數和複數形式的類別。

+ +
verbose_name = 'BetterName'
+ +

其他有用的屬性允許你為模型創建和應用新的“訪問權限”(預設權限會被自動套用),允許基於其他的字段排序,或聲明該類是”抽象的“(你無法創建的記錄基類,並將由其他型號派生)。

+ +

許多其他元數據選項控制模型中必須使用哪些數據庫以及數據的存儲方式。(如果你需要模型映射一個現有數據庫,這會有用)。

+ +

完整有用的元數據選項在這裡Model metadata options (Django docs).

+ +

方法(Methods)

+ +

一個模型也可以有方法。

+ +

最起碼,在每個模型中,你應該定義標準的Python 類方法__str__() 來為每個物件返回一個人類可讀的字符串此字符用於表示管理站點的各個記錄(以及你需要引用模型實例的任何其他位置)。通常這將返回模型中的標題或名稱字段。

+ +
def __str__(self):
+    return self.field_name
+ +

Django 方法中另一個常用方法是 get_absolute_url() ,這函數返回一個在網站上顯示個人模型記錄的 URL(如果你定義了該方法,那麼 Django 將自動在“管理站點”中添加“在站點中查看“按鈕在模型的記錄編輯欄)。get_absolute_url()的典型示例如下:

+ +
def get_absolute_url(self):
+    """Returns the url to access a particular instance of the model."""
+    return reverse('model-detail-view', args=[str(self.id)])
+
+ +
+

注意 :假設你將使用URL/myapplication/mymodelname/2 來顯示模型的單個記錄(其中“2”是id特定記錄),則需要創建一個URL映射器來將響應和id傳遞給“模型詳細視圖” (這將做出顯示記錄所需的工作)。以上示例中,reverse()函數可以“反轉”你的url映射器(在上訴命名為“model-detail-view”的案例中,以創建正確格式的URL。

+ +

當然要做這個工作,你還是要寫URL映射,視圖和模版!

+
+ +

你可以定義一些你喜歡的其他方法,並從你的代碼或模版調用它們(只要它們不帶任何參數)。

+ +

模型管理

+ +

一旦你定義了模型類,你可以使用它們來創建,更新或刪除記錄,並運行查詢獲取所有記錄或特定的記錄子集。當我們定義我們的視圖,我們將展示給你在這個教程如何去做。

+ +

創建和修改記錄

+ +

要創建一個記錄,你可以定義一個模型實例,然後呼叫 save()

+ +
# Create a new record using the model's constructor.
+record = MyModelName(my_field_name="Instance #1")
+
+# Save the object into the database.
+record.save()
+ +
+

註:如果沒有任何的欄位被宣告為主鍵,這筆新的紀錄會被自動的賦予一個主鍵並將主鍵欄命名為 id。上例的那筆資料被儲存後,試著查詢這筆紀錄會看到它被自動賦予 1 的編號。

+
+ +

你可以透過「點(dot)的語法」取得或變更這筆新資料的欄位(字段)。你需要呼叫 save() 將變更過的資料存進資料庫。

+ +
# Access model field values using Python attributes.
+print(record.id) #should return 1 for the first record.
+print(record.my_field_name) # should print 'Instance #1'
+
+# Change record by modifying the fields, then calling save().
+record.my_field_name = "New Instance Name"
+record.save()
+
+ +

搜尋紀錄

+ +

你可以使用模型的 objects 屬性(由 base class 提供)搜尋符合某個條件的紀錄。You can search for records that match a certain criteria using the model's attribute (provided by the base class).

+ +
+

Note: 要用"抽象的"模型還有欄位說明怎麼搜尋紀錄可能會有點令人困惑。我們會以一個Book模型,其包含titlegenre字段,而genre 也是一個僅有name一個字段的模型。

+
+ +

我們可以取得一個模型的所有紀錄,為一個 QuerySet 使用objects.all()。 QuerySet 是一個可迭代的物件,表示他含有多個物件,而我們可以藉由迭代/迴圈取得每個物件。

+ +
all_books = Book.objects.all()
+
+ +

Django的 filter() 方法讓我們可以透過符合特定文字或數值的字段篩選回傳的QuerySet。例如篩選書名裡有 "wild" 的書並且計算總數,如下面所示。

+ +
wild_books = Book.objects.filter(title__contains='wild')
+number_wild_books = Book.objects.filter(title__contains='wild').count()
+
+ +

要比對的字段與比對方法都要被定義在篩選的參數名稱裡,並且使用這個格式:比對字段__比對方法 (請注意上方範例中的 title 與 contains 中間隔了兩個底線唷)。在上面我們使用大小寫區分的方式比對title 。還有很多比對方式可以使用: icontains (不區分大小寫), iexact (大小寫區分且完全符合), exact (不區分大小寫但完全符合) 還有 in, gt (大於), startswith, 之類的。全部的用法在這裡。

+ +

有時候你會須要透過某個一對多的字段來篩選(例如一個 外鍵)。 這樣的狀況下,你可以使用兩個底線來指定相關模型的字段。例如透過某個特定的genre名稱篩選書籍,如下所示:

+ +
# 會比對到: Fiction, Science fiction, non-fiction etc.
+books_containing_genre = Book.objects.filter(genre__name__icontains='fiction')
+
+ +
+

Note: 你可隨心地使用雙底線 (__) 來探索更多層的關係 (ForeignKey/ManyToManyField). 例如, 一本 Book 有許多不同的 types, 其進一步定義有參數 name 關聯的"cover":type__cover__name__exact='hard'.

+
+ +

還有很多是你可以用索引(queries)來做的,包含從相關的模型做向後查詢(backwards searches)、連鎖過濾器(chaining filters)、回傳「值的小集合」等。更多資訊可以到 Making queries (Django Docs) 查詢。

+ +

定義 LocalLibrary 模型

+ +

這部份我們會開始定義圖書館的模型。

+ +

先打開 models.py (在 /locallibrary/catalog/),頁面的最上方可以看到樣板導入了 models 模組,其包含了模型的基本類別 models.Model ,能使我們的模型能夠繼承。

+ +
from django.db import models
+
+# Create your models here.
+ +

書籍類型模型 (Genre model)

+ +

複製下方 Genre 模型的程式碼,並貼在你的 models.py 檔案底部,這個模型是用來儲存書籍類型的資訊 — 例如:該本書是否為科幻小說、羅曼史、軍事歷史等。

+ +

就像先前提到的,我們以「模型」的方式建立一個書籍類型模型,而非以自由文本(free text)或者選擇列表(selection list)的方式,這樣做讓我們可以透過資料庫的形式而非硬編碼(hard coded)的方式來管理所有可能的值。

+ +
class Genre(models.Model):
+    """Model representing a book genre."""
+    name = models.CharField(max_length=200, help_text='Enter a book genre (e.g. Science Fiction)')
+
+    def __str__(self):
+        """String for representing the Model object."""
+        return self.name
+ +

此模型有一個單一的 CharField 字段(name) 被用來描述書籍類別(限制輸入字元長度最多200個,同時也有提示文本(help_text) )。

+ +

在模型最下方我們宣告一個 __str__() 方法來簡單回傳被特定一筆紀錄定義的書籍類別名稱。

+ +

因為詳細名稱(verbose name)沒有被定義,所以字段在形式上會被稱為 Name 。

+ +

書本模型 (Book model)

+ +

複製下方 Book 模型的程式碼,並貼在你的 models.py 檔案底部,這個 Book 模型一般來說代表一個可用書本的所有資訊,但並非包含特定的物理實例(physical instance)或者副本資訊(copy),此模型使用 CharField 來表示書的 title 和 isbn (國際標準書號)(note how the isbn specifies its label as "ISBN" using the first unnamed parameter because the default label would otherwise be "Isbn").,另外此模型使用 TextField 來存 summary ,因為此文本可能會很長。

+ +
from django.urls import reverse #Used to generate URLs by reversing the URL patterns
+
+class Book(models.Model):
+    """Model representing a book (but not a specific copy of a book)."""
+    title = models.CharField(max_length=200)
+    author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True)
+
+    # Foreign Key used because book can only have one author, but authors can have multiple books
+    # Author as a string rather than object because it hasn't been declared yet in the file.
+    summary = models.TextField(max_length=1000, help_text='Enter a brief description of the book')
+    isbn = models.CharField('ISBN', max_length=13, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>')
+
+    # ManyToManyField used because genre can contain many books. Books can cover many genres.
+    # Genre class has already been defined so we can specify the object above.
+    genre = models.ManyToManyField(Genre, help_text='Select a genre for this book')
+
+    def __str__(self):
+        """String for representing the Model object."""
+        return self.title
+
+    def get_absolute_url(self):
+        """Returns the url to access a detail record for this book."""
+        return reverse('book-detail', args=[str(self.id)])
+
+
+ +

「書籍類別」(genre)是一個 ManyToManyField ,因此一本書可以有很多書籍類別,而一個書結類別也能夠對應到很多本書。作者(author)被宣告為外鍵(ForeignKey),因此每本書只會有一名作者,但一名作者可能會有多本書(實際上,一本書可能會有多名作者,不過這個案例不會有,所以在別的例子這種作法可能會有問題)

+ +

在上面兩個宣告關聯性模型的敘述句內,關聯的對象都是用對象的模型類或字串的方式作為首個未具名參數的方式傳入句內做宣告。在關聯對象尚未被定義前,若要參照到該對象,必須使用該對象名稱字串的方式來宣告關聯性!還有一些 author 欄位的其它值得一提的參數:null=True 表示如果沒有作者的話,允許在資料庫中存入 Null 值;on_delete=models.SET_NULL 表示如果某筆作者紀錄被刪除的話,與該作者相關連的欄位都會被設成 Null

+ +

這個模型也定義了 __str__() ,使用書本的 title 字段來表示一筆 Book 的紀錄。而最後一個方法,get_absolute_url() ,則會回傳一個可以被用來存取該模型細節紀錄的 URL (要讓其有效運作,我們必須定義一個 URL 的映射,我們將其命名為 book-detail ,另外還得定義一個關聯示圖(view)與模板(template) )。

+ +

書本詳情模型 (BookInstance model)

+ +

接下來,複製下方 BookInstance 的模型,貼在其他模型下面,這個 BookInstance 模型表示一個特定的書籍副本(可會被某人借走),並且包含如「副本是否可用」、「預計歸還日期」、「版本說明」或「版本細節」等資訊,還有一個在圖書館中唯一的 id 。

+ +

有些字段(fields)和方法(methods)現在你也熟悉了。此模型使用了:

+ + + +
import uuid # Required for unique book instances
+
+class BookInstance(models.Model):
+    """Model representing a specific copy of a book (i.e. that can be borrowed from the library)."""
+    id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular book across whole library')
+    book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True)
+    imprint = models.CharField(max_length=200)
+    due_back = models.DateField(null=True, blank=True)
+
+    LOAN_STATUS = (
+        ('m', 'Maintenance'),
+        ('o', 'On loan'),
+        ('a', 'Available'),
+        ('r', 'Reserved'),
+    )
+
+    status = models.CharField(
+        max_length=1,
+        choices=LOAN_STATUS,
+        blank=True,
+        default='m',
+        help_text='Book availability',
+    )
+
+    class Meta:
+        ordering = ['due_back']
+
+    def __str__(self):
+        """String for representing the Model object."""
+        return f'{self.id} ({self.book.title})'
+ +

我們額外宣告了一些新的字段(field)類別(types):

+ + + +

而 __str__() 模型用來表示 BookInstance 這個物件的「唯一 ID」和「相關之 Book 書本名稱(title)」的組合。

+ +
+

Note: 關於 Python 的小提醒:

+ + +
+ +

作者模型(Author model)

+ +

複製下方 Author 的模型程式碼並貼在 models.py 文件的最下方。

+ +

現在所有的字段(fields)與方法(methods)你應該都熟悉了,此模型定義了作者的「名」、「姓」、「出生年月日」、「死亡日期(非必填)」。該模型也指定,預設情況下,__str__() 方法會回傳作者姓名(按照姓、名排序)。而 get_absolute_url() 方法會反轉 author-detail 的URL映射,來獲得顯示單個作者的URL。

+ +
class Author(models.Model):
+    """Model representing an author."""
+    first_name = models.CharField(max_length=100)
+    last_name = models.CharField(max_length=100)
+    date_of_birth = models.DateField(null=True, blank=True)
+    date_of_death = models.DateField('Died', null=True, blank=True)
+
+    class Meta:
+        ordering = ['last_name', 'first_name']
+
+    def get_absolute_url(self):
+        """Returns the url to access a particular author instance."""
+        return reverse('author-detail', args=[str(self.id)])
+
+    def __str__(self):
+        """String for representing the Model object."""
+        return f'{self.last_name}, {self.first_name}'
+
+
+ +

再次執行資料庫遷移(database migrations)

+ +

你的所有模型都建立好了,現在必須再次執行你的資料庫 migrations 指令來將這些修改內容更信到資料庫中。

+ +
python3 manage.py makemigrations
+python3 manage.py migrate
+ +

語言模型(Language model) — 挑戰

+ +

請想像一下,現在來了一位善心人士捐了一堆用不同語言寫的書(例如:波斯語),而你的挑戰是必須制定一個最好在我們的圖說館網站呈現的方式,並把它做成模組。

+ +

幾件事情需要思考:

+ + + +

當你決定好了,就開始動手吧!你可以在Github的這裡看到我們是怎麼思考的。

+ + + + + +

小結

+ +

在這篇文章我們學到如何定義模型,並且利用這些資訊來設計與實作適合的模型給 LocalLibrary 網站。

+ +

再來我們要稍微撇開建立網站,先來看看 Django 的管理站(Django Administration site),這個管理站能讓我們加入一些資料到圖書館中,讓我們再來能夠透過「示圖(views)與模板(templates)」(當然我們現在都還沒建立)來展示。

+ +

延伸閱讀

+ + + +

{{PreviousMenuNext("Learn/Server-side/Django/skeleton_website", "Learn/Server-side/Django/Admin_site", "Learn/Server-side/Django")}}

+ +

In this module

+ + diff --git a/files/zh-tw/learn/server-side/django/sessions/index.html b/files/zh-tw/learn/server-side/django/sessions/index.html new file mode 100644 index 0000000000..86b534adaf --- /dev/null +++ b/files/zh-tw/learn/server-side/django/sessions/index.html @@ -0,0 +1,185 @@ +--- +title: 'Django Tutorial Part 7: Sessions framework' +slug: Learn/Server-side/Django/Sessions +translation_of: Learn/Server-side/Django/Sessions +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Django/Generic_views", "Learn/Server-side/Django/authentication_and_sessions", "Learn/Server-side/Django")}}
+ +

本教程擴展了我們的LocalLibrary 網站,為主頁添加了一個基於會話的訪問計數器。這是一個相對簡單的例子,但它確實顯示了,如何使用會話框架,為匿名用戶提供持久的行為。

+ + + + + + + + + + + + +
Prerequisites:Complete all previous tutorial topics, including Django Tutorial Part 6: Generic list and detail views
Objective:To understand how sessions are used.
+ +

概覽

+ +

我們在之前的教程中創建的LocalLibrary 網站允許用戶瀏覽目錄中的書籍和作者。 雖然內容是從數據庫動態生成的,但每個用戶在使用該網站時基本上都可以訪問相同的頁面和信息類型。

+ +

在一個"真實"的庫中,您可能希望根據用戶以前對網站的使用,首選項等為單個用戶提供定制的體驗。例如,您可以隱藏或存儲用戶下次訪問網站時之前已確認的警告消息,或尊重他們的偏好(例如,他們希望在每個頁面上顯示的搜索結果的數量)。

+ +

會話框架允許您實現這種行為,從而允許您基於每個站點訪問者存儲和檢索任意數據。

+ +

What are sessions?

+ +

Web瀏覽器和服務器之間的所有通信都是通過HTTP協議進行的,該協議是無狀態的。該協議是無狀態的事實意味著客戶端和服務器之間的消息是完全相互獨立的-沒有基於先前消息的“序列”或行為的概念。因此,如果您想擁有一個跟踪與客戶之間正在進行的關係的站點,則需要自己實施。

+ +

會話是Django(以及大多數Internet)使用的機制,用於跟踪站點與特定瀏覽器之間的“狀態”。會話允許您在每個瀏覽器中存儲任意數據,並且只要瀏覽器連接,該數據就可用於站點。然後,與會話相關聯的單個數據項被一個``鍵''引用,該鍵既用於存儲又用於檢索數據。

+ +

Django使用包含特殊會話ID的cookie來標識每個瀏覽器及其與站點的關聯會話。默認情況下,實際會話數據默認存儲在站點數據庫中(這比將數據存儲在cookie中更安全,因為cookie在cookie中更容易受到惡意用戶的攻擊)。您可以將Django配置為將會話數據存儲在其他位置(緩存,文件或是“安全” Cookie),但是默認位置是一個很好且相對安全的選擇。

+ +

Enabling sessions

+ +

當我們創建框架網站時(在教程2中),將自動啟用會話。

+ +

在項目文件的INSTALLED_APPS 和MIDDLEWARE 部分中進行配置(locallibrary/locallibrary/settings.py),如下所示:

+ +
INSTALLED_APPS = [
+    ...
+    'django.contrib.sessions',
+    ....
+
+MIDDLEWARE = [
+    ...
+    'django.contrib.sessions.middleware.SessionMiddleware',
+    ....
+ +

Using sessions

+ +

您可以從request 參數(作為視圖的第一個參數傳入的HttpRequest )中訪問視圖中的session 屬性。 此會話屬性表示與當前用戶的特定連接(或更確切地說,與當前瀏覽器的連接,由該站點的瀏覽器cookie中的會話ID標識)。

+ +

session 屬性是一個類似於字典的對象,您可以在視圖中隨意讀取和寫入多次,並根據需要對其進行修改。 您可以執行所有正常的字典操作,包括清除所有數據,測試是否存在鍵,循環訪問數據等。儘管如此,在大多數情況下,您只會使用標準的``字典''API來獲取和設置值。

+ +

下面的代碼片段顯示瞭如何獲取,設置和刪除與當前會話(瀏覽器)相關的鍵“ my_car”的某些數據。

+ +
+

注意: Django的一大優點是,您無需考慮將會話綁定到視圖中當前請求的機制。 如果我們在視圖中使用以下片段,我們將知道有關my_car 的信息僅與發送當前請求的瀏覽器相關聯。

+
+ +
# Get a session value by its key (e.g. 'my_car'), raising a KeyError if the key is not present
+my_car = request.session['my_car']
+
+# Get a session value, setting a default if it is not present ('mini')
+my_car = request.session.get('my_car', 'mini')
+
+# Set a session value
+request.session['my_car'] = 'mini'
+
+# Delete a session value
+del request.session['my_car']
+
+ +

該API還提供了許多其他方法,這些方法主要用於管理關聯的會話cookie。 例如,有一些方法可以測試客戶端瀏覽器是否支持cookie,設置和檢查cookie到期日期以及從數據存儲中清除過期的會話。 您可以在如 How to use sessions 找到完整的API(Django文檔)。

+ +

Saving session data

+ +

默認情況下,當會話已被修改(分配)或刪除時,Django僅保存到會話數據庫並將會話cookie發送給客戶端。 如果您要使用上一節中所示的會話密鑰更新某些數據,則無需擔心! 例如:

+ +
# This is detected as an update to the session, so session data is saved.
+request.session['my_car'] = 'mini'
+ +

如果您要更新會話數據中的某些信息,則Django將不會識別您已對會話進行了更改並保存了數據(例如,如果要在“ my_car”數據中更改“ wheels”數據, 如下所示)。 在這種情況下,您需要將會話明確標記為已修改。

+ +
# Session object not directly modified, only data within the session. Session changes not saved!
+request.session['my_car']['wheels'] = 'alloy'
+
+# Set session as modified to force data updates/cookie to be saved.
+request.session.modified = True
+
+ +
+

注意:您可以更改行為,以便站點可以通過在您的項目設置(locallibrary/locallibrary/settings.py)中添加SESSION_SAVE_EVERY_REQUEST = True 來更新每個請求的數據庫/發送cookie。

+
+ +

Simple example — getting visit counts

+ +

作為一個簡單的真實示例,我們將更新我們的庫以告知當前用戶他們訪問LocalLibrary主頁的次數。

+ +

打開/ /locallibrary/catalog/views.py,然後進行以下粗體顯示的更改。

+ +
def index(request):
+    ...
+
+    num_authors = Author.objects.count()  # The 'all()' is implied by default.
+
+    # Number of visits to this view, as counted in the session variable.
+    num_visits = request.session.get('num_visits', 0)
+    request.session['num_visits'] = num_visits + 1
+
+    context = {
+        'num_books': num_books,
+        'num_instances': num_instances,
+        'num_instances_available': num_instances_available,
+        'num_authors': num_authors,
+        'num_visits': num_visits,
+    }
+
+    # Render the HTML template index.html with the data in the context variable.
+    return render(request, 'index.html', context=context)
+ +

在這裡,我們首先獲取'num_visits'會話密鑰的值,如果之前未設置,則將其設置為0。 每次接收到請求時,我們都將增加該值並將其存儲回會話中(對於下一次用戶訪問該頁面)。 然後將num_visits 變量傳遞到我們的上下文變量中的模板。

+ +
+

注意:我們也可能會在此處測試瀏覽器是否甚至支持cookie(例如,請參閱How to use sessions)或設計我們的UI,以便無論是否支持cookie都無關緊要。

+
+ +

將以下區塊底部看到的行添加到``動態內容''部分底部的主HTML模板(/locallibrary/catalog/templates/index.html)中以顯示上下文變量:

+ +
<h2>Dynamic content</h2>
+
+<p>The library has the following record counts:</p>
+<ul>
+  <li><strong>Books:</strong> \{{ num_books }}</li>
+  <li><strong>Copies:</strong> \{{ num_instances }}</li>
+  <li><strong>Copies available:</strong> \{{ num_instances_available }}</li>
+  <li><strong>Authors:</strong> \{{ num_authors }}</li>
+</ul>
+
+<p>You have visited this page \{{ num_visits }}{% if num_visits == 1 %} time{% else %} times{% endif %}.</p>
+
+ +

保存更改,然後重新啟動測試服務器。 每次刷新頁面時,數字都會更新。

+ +

總結

+ +

現在,您知道使用會話來改善與匿名用戶的交互是多麼容易。

+ +

在接下來的文章中,我們將說明身份驗證和授權(權限)框架,並向您展示如何支持用戶帳戶。

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/Server-side/Django/Generic_views", "Learn/Server-side/Django/Authentication", "Learn/Server-side/Django")}}

+ +

In this module

+ + diff --git a/files/zh-tw/learn/server-side/django/skeleton_website/index.html b/files/zh-tw/learn/server-side/django/skeleton_website/index.html new file mode 100644 index 0000000000..b57b351eae --- /dev/null +++ b/files/zh-tw/learn/server-side/django/skeleton_website/index.html @@ -0,0 +1,388 @@ +--- +title: 'Django 教學 2: 創建一個骨架網站' +slug: Learn/Server-side/Django/skeleton_website +translation_of: Learn/Server-side/Django/skeleton_website +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Django/Tutorial_local_library_website", "Learn/Server-side/Django/Models", "Learn/Server-side/Django")}}
+ +

Django 教學的第二篇文章,會展示怎樣創建一個網站的"框架",在這個框架的基礎上,你可以繼續填充整站使用的 settings, urls,模型(models),視圖(views)和模板(templates )。

+ + + + + + + + + + + + +
前提:創建 Django 的開發環境。複習 Django 教學。
目標:能夠使用 Django 提供的工具,搭建你自己的網站。
+ +

概覽

+ +

這篇文章會展示怎樣創建一個網站的"框架",在這個框架的基礎上,你可以繼續填充整站使用的settings, urls,模型(models),視圖(views)和模板(templates)(我們會在接下來的文章裡討論)。

+ +

搭建 “框架” 的過程很直接:

+ +
    +
  1. 使用 django-admin工具創建工程的文件夾,基本的文件模板和工程管理腳本(manage.py)。
  2. +
  3. manage.py 創建一個或多個應用。 +
    +

    注意:一個網站可能由多個部分組成,比如,主要頁面,博客,wiki,下載區域等。Django鼓勵將這些部分作為分開的應用開發。如果這樣的話,在需要可以在不同的工程中復用這些應用。

    +
    +
  4. +
  5. 工程裡註冊新的應用。
  6. +
  7. 為每個應用分配url。
  8. +
+ +

為  locallibrary  這個項目創建的網站文件夾和它的工程文件夾都命名為locallibrary我們只創建一個名為catalog的應用。最高層的項目文件結構如下所示:

+ +
locallibrary/         # Website foldermanage.py         # Script to run Django tools for this project (created using django-admin)
+    locallibrary/     # Website/project folder (created using django-admin)
+    catalog/          # Application folder (created using manage.py)
+
+ +

接下來的部分,會詳細討論創建網站框架的過程,並會展示怎麼測試這些變化。最後,我們會討論在這個階段裡,你可以設置的全站配置。

+ +

創建專案項目

+ +

首先打開命令提示符/終端,確保您在虛擬環境中,導航到您要存放Django應用程序的位置(在文檔文件夾中,輕鬆找到它的位置),並為您的新網站,創建一個文件夾(在這種情況下:locallibrary)。然後使用cd命令進入該文件夾:

+ +
mkdir locallibrary
+cd locallibrary
+ +

django-admin startproject命令創建新項目,並進入該文件夾。

+ +
django-admin startproject locallibrary
+cd locallibrary
+ +

django-admin工具會創建如下所示的文件夾結構

+ +
locallibrary/
+    manage.py
+    locallibrary/
+        __init__.py
+        settings.py
+        urls.py
+        wsgi.py
+ +

locallibrary項目的子文件夾是整個網站的進入點:

+ + + +

manage.py腳本可以創建應用,和資料庫通訊,啟動開發用網絡服務器。

+ +

創建 catalog 應用

+ +

接下來,在locallibrary項目裡,使用下面的命令創建catalog應用(和您項目的manage.py在同一個文件夾下)

+ +
python3 manage.py startapp catalog
+ +
+

注意: Linux/Mac OS X應用可以使用上面的命令。在windows平台下應該改為: py -3 manage.py startapp catalog

+ +

如果你是windows系統,在這個部分用py -3替代python3

+ +

如果您使用的是Python 3.7.0,則應使用py manage.py startapp catalog

+
+ +

這個工具創建了一個新的文件夾,並為該應用創建了不同的文件(下面黑體所示)。絕大多數文件的命名和它們的目的有關(比如視圖函數就是views.py,模型就是models.py,測試是tests.py,網站管理設置是admin.py,註冊應用是apps.py),並且還包含了為項目所用的最小模板。

+ +

執行命令後的文件夾結構如下所示:

+ +
locallibrary/
+    manage.py
+    locallibrary/
+    catalog/
+        admin.py
+        apps.py
+        models.py
+        tests.py
+        views.py
+        __init__.py
+        migrations/
+
+ +

除上面所說的文件外,我們還有:

+ + + +
+

注意 :你注意到上面的文件裡有些缺失嘛?儘管有了 views 和 models 的文件,可是 url 映射,網站模板,靜態文件在哪裡呢?我們會在接下來的部分展示如何創建它們(並不是每個網站都需要,不過這個例子需要)。

+
+ +

註冊catalog應用

+ +

既然應用已經創建好了,我們還必須在項目裡註冊它,以便工具在運行時它會包括在裡面(比如在數據庫裡添加模型時)。在項目的settings裡,把應用添加進INSTALLED_APPS ,就完成了註冊。

+ +

打開項目設置文件  locallibrary/locallibrary/settings.py找到   INSTALLED_APPS 列表裡的定義。如下所示,在列表的最後添加新的一行。

+ +
INSTALLED_APPS = [
+    'django.contrib.admin',
+    'django.contrib.auth',
+    'django.contrib.contenttypes',
+    'django.contrib.sessions',
+    'django.contrib.messages',
+    'django.contrib.staticfiles',
+    'catalog.apps.CatalogConfig', 
+]
+ +

新的這行,詳細說明了應用配置文件在( CatalogConfig/locallibrary/catalog/apps.py  裡,當你創建應用時就完成了這個過程。

+ +
+

注意 :注意到INSTALLED_APPS已经有许多其他的应用了 (還有 MIDDLEWARE,在settings的下面)。這些應用為   Django administration site  提供了支持和許多功能(包括會話,認證系統等)。

+
+ +

配置資料庫

+ +

現在可以為項目配置資料庫了——為了避免性能上的差異,最好在生產和開發中使用同一種資料庫。你可以在資料庫  裡找到不同的設置方法(Django文檔)。 

+ +

在這個項目裡,我們使用SQLite。因為在展示用的數據庫中,我們不會有很多並發存取的行為。同時,也因為SQLite不需要額外的配置工作。你可以在settings.py裡看到這個數據庫怎樣配置的。(更多信息如下所示)

+ +
DATABASES = {
+    'default': {
+        'ENGINE': 'django.db.backends.sqlite3',
+        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
+    }
+}
+
+ +

因為我們使用SQLite,不需要其他的設置了。我們繼續吧!

+ +

其他項目設置

+ +

settings.py裡還包括其他的一些設置,現在只需要改變時區 —改為和標準tz時區數據表  裡的字符串相同就可以了(數據表裡的TZ列有你想要的時區)。TIME_ZONE的值改為你的時區,比如

+ +
TIME_ZONE = 'Europe/London'
+ +

有兩個設置你現在不會用到,不過你應該留意:

+ + + +

鏈接URL映射器

+ +

在項目文件夾裡,創建網站時同時生成了URL映射器(urls.py)。儘管你可以用它來管理所有的URL映射,但是更常用的做法是把URL映射留到它們相關的應用中。

+ +

打開locallibrary/locallibrary/urls.py  注意指導文字解釋了一些使用URL映射器的方法。

+ +
"""locallibrary URL Configuration
+
+The `urlpatterns` list routes URLs to views. For more information please see:
+    https://docs.djangoproject.com/en/2.0/topics/http/urls/
+Examples:
+Function views
+    1. Add an import:  from my_app import views
+    2. Add a URL to urlpatterns:  path('', views.home, name='home')
+Class-based views
+    1. Add an import:  from other_app.views import Home
+    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
+Including another URLconf
+    1. Import the include() function: from django.urls import include, path
+    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
+"""
+from django.contrib import admin
+from django.urls import path
+
+urlpatterns = [
+    path('admin/', admin.site.urls),
+]
+
+ +

URL映射通過urlpatterns 變量管理,它是一個path()函數的Python列表。每個path()函數,要么將URL式樣(URL pattern)關聯到特定視圖( specific view),當模式匹配時將會顯示,要么關聯到某個URL式樣列表的測試代碼。(第二種情況下,URL式樣是目標模型裡的“基本URL”). urlpatterns 列表初始化定義了單一函數,把所有帶有 'admin/' 模式的 URL,映射到admin.site.urls。這個函數,包含了Administration應用自己的URL映射定義。

+ +
+

注意: path()中的路由是一個字符串,用於定義要匹配的URL模式。該字符串可能包括一個命名變量(在尖括號中),例如'catalog/<id>/'。此模式將匹配 /catalog/any_chars/ 等URL,並將any_chars 作為參數名稱為id 的字符串,傳遞給視圖。我們將在後面的主題中,進一步討論路徑方法和路由模式

+
+ +

urlpatterns 列表的下面一行,插入下面的代码。這個新項目包括一個 path() ,它使用模式 catalog/ 轉發請求到模塊 catalog.urls(具有相對 URL /catalog/urls.py 的文件)。

+ +
# Use include() to add paths from the catalog application
+from django.conf.urls import include
+from django.urls import path
+
+urlpatterns += [
+    path('catalog/', include('catalog.urls')),
+]
+
+ +

現在我們把我們網站的根URL(例如127.0.0.1:8000),重新導向URL 127.0.0.1:8000/catalog/;這是項目中唯一的應用,所以我們最好這樣做。為了完成這個目標,我們使用一個特別的視圖函數( RedirectView),當path()函數中的 url 式樣被識別以後(在這個例子中是根 url),就會把第一個參數,也就是新的相對 URL ,重定向到(/catalog/)。

+ +

把下面的代碼加到文件最後:

+ +
#Add URL maps to redirect the base URL to our application
+from django.views.generic import RedirectView
+urlpatterns += [
+    path('', RedirectView.as_view(url='/catalog/')),
+]
+ +

將路徑函數的第一個參數留空,用以表示'/'。如果您將第一個參數寫為'/',Django會在您啟動開發服務器時給出以下警告:

+ +
System check identified some issues:
+
+WARNINGS:
+?: (urls.W002) Your URL pattern '/' has a route beginning with a '/'.
+Remove this slash as it is unnecessary.
+If this pattern is targeted in an include(), ensure the include() pattern has a trailing '/'.
+
+ +

Django默認不提供CSS,JavaScript和圖像等靜態文件,但在創建站點時,開發Web服務器這樣做是有用的。作為此URL映射器的最終添加,您可以通過附加以下幾行,在開發期間啟用靜態文件的提供。

+ +

現在將以下最終區塊,添加到文件的底部:

+ +
# Use static() to add url mapping to serve static files during development (only)
+from django.conf import settings
+from django.conf.urls.static import static
+
+urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
+
+ +
+

注意: 有許多方法可以擴充urlpatterns列表(上面我們只是使用+= 運算符,附加一個新的列表項,來清楚地分隔舊代碼和新代碼)。我們可以改為在原始列表定義中,包含這個新的模式映射:

+ +
urlpatterns = [
+    path('admin/', admin.site.urls),
+    path('catalog/', include('catalog.urls')),
+    path('', RedirectView.as_view(url='/catalog/', permanent=True)),
+] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
+
+ +

此外,我們將導入行(from django.urls import include)包含在使用它的代碼中(因此很容易看到我們添加的內容),但通常將所有導入行包含在一個Python文件的頂部。

+
+ +

最後一步,在catalog文件夾中,創建一個名為urls.py的文件,並添加以下文本,以定義(空)導入的urlpatterns。這是我們在構建應用程序時,添加模式的地方。

+ +
from django.urls import path
+from . import views
+
+
+urlpatterns = [
+
+]
+
+ +

測試網站框架

+ +

現在我們有了一個完整的框架項目。這個網站現在還什麼都不能做,但是我們仍然要運行,以確保我們的更改是有效的。

+ +

在運行前,我們應該先運行數據庫遷移這會更新我們的數據庫並且包含所有安裝的應用(同時去除一些警告)。

+ +

運行資料庫遷移

+ +

Django使用對象關係映射器(ORM),將Django代碼中的模型定義,映射到底層資料庫使用的數據結構。當我們更改模型定義時,Django會跟踪更改,並創建資料庫遷移腳本(位於 /locallibrary/catalog/migrations/ ),來自動遷移資料庫中的底層數據結構。

+ +

當我們創建網站時,Django會自動添加一些模型,供網站的管理部分使用(稍後我們會解釋)。運行以下命令,來定義資料庫中這些模型的表(確認你位於包含 manage.py 的目錄中):

+ +
python3 manage.py makemigrations
+python3 manage.py migrate
+
+ +
+

重要: 每次模型改變,都需要運行以上命令,來影響需要存放的數據結構(包括添加和刪除整個模型和單個字段)。

+
+ +

makemigrations命令,創建(但不實施)項目中安裝的所有應用程序的遷移(你可以指定應用程序名稱,也可以為單個項目運行遷移)。這讓你有機會在應用這些遷移之前,檢查這些遷移代碼—當你是Django專家時,你可以選擇稍微調整它們。

+ +

這個 migrate命令,真正對你的資料庫實施遷移(Django跟踪哪些已添加到當前資料庫)。

+ +
+

注意: 參見 Migrations (Django 文件) ,了解較少使用的遷移命令的其他信息。

+
+ +

運行網站

+ +

在開發期間,你首先要使用開發網頁服務器,然後用你本機的瀏覽器觀看,來測試你的網站。

+ +
+

注意: 這個開發網頁服務器並不夠強大,不足以用於生產使用,但是它使你在開發期間,能非常容易獲得你的 Django 網站和運行它,以此來進行快速測試。默認情況下,服務器會開通(http://127.0.0.1:8000/),但你也可以選擇其他端口。有關更多信息,查閱(django-admin and manage.py: runserver)(Django docs).

+
+ +

通過如下runserver命令,運行開發網頁服務器。(同樣的要在manage.py的目錄)

+ +
python3 manage.py runserver
+
+ Performing system checks...
+
+ System check identified no issues (0 silenced).
+ September 22, 2016 - 16:11:26
+ Django version 1.10, using settings 'locallibrary.settings'
+ Starting development server at http://127.0.0.1:8000/
+ Quit the server with CTRL-BREAK.
+
+ +

一旦服務器運行,你可以用你的瀏覽器導航到http://127.0.0.1:8000/ 查看。你應該會看到一個錯誤頁面,如下。

+ +

Django Debug page for Django 2.0

+ +

別擔心,這個錯誤頁面是預期的結果。因為我們沒有在 catalogs.urls模塊中,定義任何頁面或網址(即是當我們使用一個指向根目錄的URL時,會被重新定向的地方)。

+ +
+

注意: 上面的頁面,演示了一個很棒的Django功能 - 自動除錯日誌記錄。只要找不到頁面,或者代碼引發任何錯誤,就會顯示錯誤畫面,其中包含有用的信息。在這種情況下,我們可以看到我們提供的URL,與我們的任何URL模式都不匹配(如列出的那樣)。在生產期間(當我們將網站放在網上時),日誌記錄將被關閉,在這種情況下,將提供信息量較少、但用戶友好的頁面。

+
+ +

這個時候,我們知道Django正在工作!

+ +
+

注意: 在進行重大更改時,你應該重新運行遷移,並重新測試站點。這不需要很長時間!

+
+ +

挑戰自我

+ +

catalog/  目錄包含應用程序的視圖、模型、和應用的其他部分,你可以打開這些文件並查看樣板。

+ +

如上所述,管理站點的URL映射,已經添加到項目的 urls.py在瀏覽器中查看管理區域,看看會發生什麼(你可以從上面映射,推斷正確的URL)。

+ + + +

總結

+ +

你現在已經創建了一個完整的骨架網站項目,你可以繼續加入網址、模型、視圖、和模版。

+ +

現在,Local Library website的骨架已經完成並運行了,是時候開始寫些代碼,讓網站做些它應該做的事了。

+ +

參見

+ + + +

{{PreviousMenuNext("Learn/Server-side/Django/Tutorial_local_library_website", "Learn/Server-side/Django/Models", "Learn/Server-side/Django")}}

+ + + +

本教程連結

+ + diff --git a/files/zh-tw/learn/server-side/django/testing/index.html b/files/zh-tw/learn/server-side/django/testing/index.html new file mode 100644 index 0000000000..d559585a50 --- /dev/null +++ b/files/zh-tw/learn/server-side/django/testing/index.html @@ -0,0 +1,907 @@ +--- +title: 'Django Tutorial Part 10: Testing a Django web application' +slug: Learn/Server-side/Django/Testing +translation_of: Learn/Server-side/Django/Testing +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Django/Forms", "Learn/Server-side/Django/Deployment", "Learn/Server-side/Django")}}
+ +

隨著網站的增長,他們越來越難以手動測試。不僅要進行更多的測試,而且隨著組件之間的互動,變得越來越複雜,一個區域的小改變,可能會影響到其他區域,所以需要做更多的改變,來確保一切正常運行,並且在進行更多更改時,不會引入錯誤。減輕這些問題的一種方法,是編寫自動化測試,每當您進行更改時,都可以輕鬆可靠地運行測試。本教程演示如何使用 Django 的測試框架,自動化您的網站的單元測試。

+ + + + + + + + + + + + +
Prerequisites:Complete all previous tutorial topics, including Django Tutorial Part 9: Working with forms.
Objective:To understand how to write unit tests for Django-based websites.
+ +

Overview

+ +

The LocalLibrary currently has pages to display lists of all books and authors, detail views for Book and Author items, a page to renew BookInstances, and pages to create, update, and delete Author items (and Book records too, if you completed the challenge in the forms tutorial). Even with this relatively small site, manually navigating to each page and superficially checking that everything works as expected can take several minutes. As we make changes and grow the site, the time required to manually check that everything works "properly" will only grow. If we were to continue as we are, eventually we'd be spending most of our time testing, and very little time improving our code.

+ +

Automated tests can really help with this problem! The obvious benefits are that they can be run much faster than manual tests, can test to a much lower level of detail, and test exactly the same functionality every time (human testers are nowhere near as reliable!) Because they are fast, automated tests can be executed more regularly, and if a test fails, they point to exactly where code is not performing as expected.

+ +

In addition, automated tests can act as the first real-world "user" of your code, forcing you to be rigorous about defining and documenting how your website should behave. Often they are basis for your code examples and documentation. For these reasons, some software development processes start with test definition and implementation, after which the code is written to match the required behavior (e.g. test-driven and behaviour-driven development).

+ +

This tutorial shows how to write automated tests for Django, by adding a number of tests to the LocalLibrary website.

+ +

Types of testing

+ +

There are numerous types, levels, and classifications of tests and testing approaches. The most important automated tests are:

+ +
+
Unit tests
+
Verify functional behavior of individual components, often to class and function level.
+
Regression tests
+
Tests that reproduce historic bugs. Each test is initially run to verify that the bug has been fixed, and then re-run to ensure that it has not been reintroduced following later changes to the code.
+
Integration tests
+
Verify how groupings of components work when used together. Integration tests are aware of the required interactions between components, but not necessarily of the internal operations of each component. They may cover simple groupings of components through to the whole website.
+
+ +
+

Note: Other common types of tests include black box, white box, manual, automated, canary, smoke, conformance, acceptance, functional, system, performance, load, and stress tests. Look them up for more information.

+
+ +

What does Django provide for testing?

+ +

Testing a website is a complex task, because it is made of several layers of logic – from HTTP-level request handling, queries models, to form validation and processing, and template rendering.

+ +

Django provides a test framework with a small hierarchy of classes that build on the Python standard unittest library. Despite the name, this test framework is suitable for both unit and integration tests. The Django framework adds API methods and tools to help test web and Django-specific behaviour. These allow you to simulate requests, insert test data, and inspect your application's output. Django also provides an API (LiveServerTestCase) and tools for using different testing frameworks, for example you can integrate with the popular Selenium framework to simulate a user interacting with a live browser.

+ +

To write a test you derive from any of the Django (or unittest) test base classes (SimpleTestCaseTransactionTestCaseTestCaseLiveServerTestCase) and then write separate methods to check that specific functionality works as expected (tests use "assert" methods to test that expressions result in True or False values, or that two values are equal, etc.) When you start a test run, the framework executes the chosen test methods in your derived classes. The test methods are run independently, with common setup and/or tear-down behaviour defined in the class, as shown below.

+ +
class YourTestClass(TestCase):
+
+    def setUp(self):
+        #Setup run before every test method.
+        pass
+
+    def tearDown(self):
+        #Clean up run after every test method.
+        pass
+
+    def test_something_that_will_pass(self):
+        self.assertFalse(False)
+
+    def test_something_that_will_fail(self):
+        self.assertTrue(False)
+
+ +

The best base class for most tests is django.test.TestCase.  This test class creates a clean database before its tests are run, and runs every test function in its own transaction. The class also owns a test Client that you can use to simulate a user interacting with the code at the view level. In the following sections we're going to concentrate on unit tests, created using this TestCase base class.

+ +
+

Note: The django.test.TestCase class is very convenient, but may result in some tests being slower than they need to be (not every test will need to set up its own database or simulate the view interaction). Once you're familiar with what you can do with this class, you may want to replace some of your tests with the available simpler test classes.

+
+ +

What should you test?

+ +

You should test all aspects of your own code, but not any libraries or functionality provided as part of Python or Django.

+ +

So for example, consider the Author model defined below. You don't need to explicitly test that first_name and last_name have been stored properly as CharField in the database because that is something defined by Django (though of course in practice you will inevitably test this functionality during development). Nor do you need to test that the date_of_birth has been validated to be a date field, because that is again something implemented in Django.

+ +

However you should check the text used for the labels (First name, Last_name, Date of birth, Died), and the size of the field allocated for the text (100 chars), because these are part of your design and something that could be broken/changed in future.

+ +
class Author(models.Model):
+    first_name = models.CharField(max_length=100)
+    last_name = models.CharField(max_length=100)
+    date_of_birth = models.DateField(null=True, blank=True)
+    date_of_death = models.DateField('Died', null=True, blank=True)
+
+    def get_absolute_url(self):
+        return reverse('author-detail', args=[str(self.id)])
+
+    def __str__(self):
+        return '%s, %s' % (self.last_name, self.first_name)
+ +

Similarly, you should check that the custom methods get_absolute_url() and __str__() behave as required because they are your code/business logic. In the case of get_absolute_url() you can trust that the Django reverse() method has been implemented properly, so what you're testing is that the associated view has actually been defined.

+ +
+

Note: Astute readers may note that we would also want to constrain the date of birth and death to sensible values, and check that death comes after birth. In Django this constraint would be added to your form classes (although you can define validators for the fields these appear to only be used at the form level, not the model level).

+
+ +

With that in mind lets start looking at how to define and run tests.

+ +

Test structure overview

+ +

Before we go into the detail of "what to test", let's first briefly look at where and how tests are defined.

+ +

Django uses the unittest module’s built-in test discovery, which will discover tests under the current working directory in any file named with the pattern test*.py. Provided you name the files appropriately, you can use any structure you like. We recommend that you create a module for your test code, and have separate files for models, views, forms, and any other types of code you need to test. For example:

+ +
catalog/
+  /tests/
+    __init__.py
+    test_models.py
+    test_forms.py
+    test_views.py
+
+ +

Create a file structure as shown above in your LocalLibrary project. The __init__.py should be an empty file (this tells Python that the directory is a package). You can create the three test files by copying and renaming the skeleton test file /catalog/tests.py.

+ +
+

Note: The skeleton test file /catalog/tests.py was created automatically when we built the Django skeleton website. It is perfectly "legal" to put all your tests inside it, but if you test properly, you'll quickly end up with a very large and unmanageable test file.

+ +

Delete the skeleton file as we won't need it.

+
+ +

Open /catalog/tests/test_models.py. The file should import django.test.TestCase, as shown:

+ +
from django.test import TestCase
+
+# Create your tests here.
+
+ +

Often you will add a test class for each model/view/form you want to test, with individual methods for testing specific functionality. In other cases you may wish to have a separate class for testing a specific use case, with individual test functions that test aspects of that use-case (for example, a class to test that a model field is properly validated, with functions to test each of the possible failure cases). Again, the structure is very much up to you, but it is best if you are consistent.

+ +

Add the test class below to the bottom of the file. The class demonstrates how to construct a test case class by deriving from TestCase.

+ +
class YourTestClass(TestCase):
+
+    @classmethod
+    def setUpTestData(cls):
+        print("setUpTestData: Run once to set up non-modified data for all class methods.")
+        pass
+
+    def setUp(self):
+        print("setUp: Run once for every test method to setup clean data.")
+        pass
+
+    def test_false_is_false(self):
+        print("Method: test_false_is_false.")
+        self.assertFalse(False)
+
+    def test_false_is_true(self):
+        print("Method: test_false_is_true.")
+        self.assertTrue(False)
+
+    def test_one_plus_one_equals_two(self):
+        print("Method: test_one_plus_one_equals_two.")
+        self.assertEqual(1 + 1, 2)
+ +

The new class defines two methods that you can use for pre-test configuration (for example, to create any models or other objects you will need for the test):

+ + + +
+

The test classes also have a tearDown() method which we haven't used. This method isn't particularly useful for database tests, since the TestCase base class takes care of database teardown for you.

+
+ +

Below those we have a number of test methods, which use Assert functions to test whether conditions are true, false or equal (AssertTrue, AssertFalse, AssertEqual). If the condition does not evaluate as expected then the test will fail and report the error to your console.

+ +

The AssertTrue, AssertFalse, AssertEqual are standard assertions provided by unittest.  There are other standard assertions in the framework, and also Django-specific assertions to test if a view redirects (assertRedirects), to test if a particular template has been used (assertTemplateUsed), etc.

+ +
+

You should not normally include print() functions in your tests as shown above. We do that here only so that you can see the order that the setup functions are called in the console (in the following section).

+
+ +

How to run the tests

+ +

The easiest way to run all the tests is to use the command:

+ +
python3 manage.py test
+ +

This will discover all files named with the pattern test*.py under the current directory and run all tests defined using appropriate base classes (here we have a number of test files, but only /catalog/tests/test_models.py currently contains any tests.) By default the tests will individually report only on test failures, followed by a test summary.

+ +
+

If you get errors similar to: ValueError: Missing staticfiles manifest entry ... this may be because testing does not run collectstatic by default and your app is using a storage class that requires it (see manifest_strict for more information). There are a number of ways you can overcome this problem - the easiest is to simply run collectstatic before running the tests:

+ +
python3 manage.py collectstatic
+
+
+ +

Run the tests in the root directory of LocalLibrary. You should see an output like the one below.

+ +
>python3 manage.py test
+
+Creating test database for alias 'default'...
+setUpTestData: Run once to set up non-modified data for all class methods.
+setUp: Run once for every test method to setup clean data.
+Method: test_false_is_false.
+.setUp: Run once for every test method to setup clean data.
+Method: test_false_is_true.
+FsetUp: Run once for every test method to setup clean data.
+Method: test_one_plus_one_equals_two.
+.
+======================================================================
+FAIL: test_false_is_true (catalog.tests.tests_models.YourTestClass)
+----------------------------------------------------------------------
+Traceback (most recent call last):
+  File "D:\Github\django_tmp\library_w_t_2\locallibrary\catalog\tests\tests_models.py", line 22, in test_false_is_true
+    self.assertTrue(False)
+AssertionError: False is not true
+
+----------------------------------------------------------------------
+Ran 3 tests in 0.075s
+
+FAILED (failures=1)
+Destroying test database for alias 'default'...
+ +

Here we see that we had one test failure, and we can see exactly what function failed and why (this failure is expected, because False is not True!).

+ +
+

Tip: The most important thing to learn from the test output above is that it is much more valuable if you use descriptive/informative names for your objects and methods.

+
+ +

The text shown in bold above would not normally appear in the test output (this is generated by the print() functions in our tests). This shows how the setUpTestData() method is called once for the class and setUp() is called before each method.

+ +

The next sections show how you can run specific tests, and how to control how much information the tests display.

+ +

Showing more test information

+ +

If you want to get more information about the test run you can change the verbosity. For example, to list the test successes as well as failures (and a whole bunch of information about how the testing database is set up) you can set the verbosity to "2" as shown:

+ +
python3 manage.py test --verbosity 2
+ +

The allowed verbosity levels are 0, 1, 2, and 3, with the default being "1".

+ +

Running specific tests

+ +

If you want to run a subset of your tests you can do so by specifying the full dot path to the package(s), module, TestCase subclass or method:

+ +
python3 manage.py test catalog.tests   # Run the specified module
+python3 manage.py test catalog.tests.test_models  # Run the specified module
+python3 manage.py test catalog.tests.test_models.YourTestClass # Run the specified class
+python3 manage.py test catalog.tests.test_models.YourTestClass.test_one_plus_one_equals_two  # Run the specified method
+
+ +

LocalLibrary tests

+ +

Now we know how to run our tests and what sort of things we need to test, let's look at some practical examples.

+ +
+

Note: We won't write every possible test, but this should give you and idea of how tests work, and what more you can do.

+
+ +

Models

+ +

As discussed above, we should test anything that is part of our design or that is defined by code that we have written, but not libraries/code that is already tested by Django or the Python development team.

+ +

For example, consider the Author model below. Here we should test the labels for all the fields, because even though we haven't explicitly specified most of them, we have a design that says what these values should be. If we don't test the values, then we don't know that the field labels have their intended values. Similarly while we trust that Django will create a field of the specified length, it is worthwhile to specify a test for this length to ensure that it was implemented as planned.

+ +
class Author(models.Model):
+    first_name = models.CharField(max_length=100)
+    last_name = models.CharField(max_length=100)
+    date_of_birth = models.DateField(null=True, blank=True)
+    date_of_death = models.DateField('Died', null=True, blank=True)
+
+    def get_absolute_url(self):
+        return reverse('author-detail', args=[str(self.id)])
+
+    def __str__(self):
+        return '%s, %s' % (self.last_name, self.first_name)
+ +

Open our /catalog/tests/test_models.py, and replace any existing code with the following test code for the Author model.

+ +

Here you'll see that we first import TestCase and derive our test class (AuthorModelTest) from it, using a descriptive name so we can easily identify any failing tests in the test output. We then call setUpTestData() to create an author object that we will use but not modify in any of the tests.

+ +
from django.test import TestCase
+
+# Create your tests here.
+
+from catalog.models import Author
+
+class AuthorModelTest(TestCase):
+
+    @classmethod
+    def setUpTestData(cls):
+        #Set up non-modified objects used by all test methods
+        Author.objects.create(first_name='Big', last_name='Bob')
+
+    def test_first_name_label(self):
+        author=Author.objects.get(id=1)
+        field_label = author._meta.get_field('first_name').verbose_name
+        self.assertEquals(field_label,'first name')
+
+    def test_date_of_death_label(self):
+        author=Author.objects.get(id=1)
+        field_label = author._meta.get_field('date_of_death').verbose_name
+        self.assertEquals(field_label,'died')
+
+    def test_first_name_max_length(self):
+        author=Author.objects.get(id=1)
+        max_length = author._meta.get_field('first_name').max_length
+        self.assertEquals(max_length,100)
+
+    def test_object_name_is_last_name_comma_first_name(self):
+        author=Author.objects.get(id=1)
+        expected_object_name = '%s, %s' % (author.last_name, author.first_name)
+        self.assertEquals(expected_object_name,str(author))
+
+    def test_get_absolute_url(self):
+        author=Author.objects.get(id=1)
+        #This will also fail if the urlconf is not defined.
+        self.assertEquals(author.get_absolute_url(),'/catalog/author/1')
+ +

The field tests check that the values of the field labels (verbose_name) and that the size of the character fields are as expected. These methods all have descriptive names, and follow the same pattern:

+ +
author=Author.objects.get(id=1)   # Get an author object to test
+field_label = author._meta.get_field('first_name').verbose_name   # Get the metadata for the required field and use it to query the required field data
+self.assertEquals(field_label,'first name')  # Compare the value to the expected result
+ +

The interesting things to note are:

+ + + +
+

Note: Tests for the last_name and date_of_birth labels, and also the test for the length of the last_name field have been omitted. Add your own versions now, following the naming conventions and approaches shown above.

+
+ +

We also need to test our custom methods. These essentially just check that the object name was constructed as we expected using "Last Name", "First Name" format, and that the URL we get for an Author item is as we would expect.

+ +
def test_object_name_is_last_name_comma_first_name(self):
+    author=Author.objects.get(id=1)
+    expected_object_name = '%s, %s' % (author.last_name, author.first_name)
+    self.assertEquals(expected_object_name,str(author))
+
+def test_get_absolute_url(self):
+    author=Author.objects.get(id=1)
+    #This will also fail if the urlconf is not defined.
+    self.assertEquals(author.get_absolute_url(),'/catalog/author/1')
+ +

Run the tests now. If you created the Author model as we described in the models tutorial it is quite likely that you will get an error for the date_of_death label as shown below. The test is failing because it was written expecting the label definition to follow Django's convention of not capitalising the first letter of the label (Django does this for you).

+ +
======================================================================
+FAIL: test_date_of_death_label (catalog.tests.test_models.AuthorModelTest)
+----------------------------------------------------------------------
+Traceback (most recent call last):
+  File "D:\...\locallibrary\catalog\tests\test_models.py", line 32, in test_date_of_death_label
+    self.assertEquals(field_label,'died')
+AssertionError: 'Died' != 'died'
+- Died
+? ^
++ died
+? ^
+ +

This is a very minor bug, but it does highlight how writing tests can more thoroughly check any assumptions you may have made.

+ +
+

Note: Change the label for the date_of_death field (/catalog/models.py) to "died" and re-run the tests.

+
+ +

The patterns for testing the other models are similar so we won't continue to discuss these further. Feel free to create your own tests for the our other models.

+ +

Forms

+ +

The philosophy for testing your forms is the same as for testing your models; you need to test anything that you've coded or your design specifies, but not the behaviour of the underlying framework and other third party libraries.

+ +

Generally this means that you should test that the forms have the fields that you want, and that these are displayed with appropriate labels and help text. You don't need to verify that Django validates the field type correctly (unless you created your own custom field and validation) — i.e. you don't need to test that an email field only accepts emails. However you would need to test any additional validation that you expect to be performed on the fields and any messages that your code will generate for errors.

+ +

Consider our form for renewing books. This has just one field for the renewal date, which will have a label and help text that we will need to verify.

+ +
class RenewBookForm(forms.Form):
+    """
+    Form for a librarian to renew books.
+    """
+    renewal_date = forms.DateField(help_text="Enter a date between now and 4 weeks (default 3).")
+
+    def clean_renewal_date(self):
+        data = self.cleaned_data['renewal_date']
+
+        #Check date is not in past.
+        if data < datetime.date.today():
+            raise ValidationError(_('Invalid date - renewal in past'))
+        #Check date is in range librarian allowed to change (+4 weeks)
+        if data > datetime.date.today() + datetime.timedelta(weeks=4):
+            raise ValidationError(_('Invalid date - renewal more than 4 weeks ahead'))
+
+        # Remember to always return the cleaned data.
+        return data
+ +

Open our /catalog/tests/test_forms.py file and replace any existing code with the following test code for the RenewBookForm form. We start by importing our form and some Python and Django libraries to help test time-related functionality. We then declare our form test class in the same way as we did for models, using a descriptive name for our TestCase-derived test class.

+ +
from django.test import TestCase
+
+# Create your tests here.
+
+import datetime
+from django.utils import timezone
+from catalog.forms import RenewBookForm
+
+class RenewBookFormTest(TestCase):
+
+    def test_renew_form_date_field_label(self):
+        form = RenewBookForm()
+        self.assertTrue(form.fields['renewal_date'].label == None or form.fields['renewal_date'].label == 'renewal date')
+
+    def test_renew_form_date_field_help_text(self):
+        form = RenewBookForm()
+        self.assertEqual(form.fields['renewal_date'].help_text,'Enter a date between now and 4 weeks (default 3).')
+
+    def test_renew_form_date_in_past(self):
+        date = datetime.date.today() - datetime.timedelta(days=1)
+        form_data = {'renewal_date': date}
+        form = RenewBookForm(data=form_data)
+        self.assertFalse(form.is_valid())
+
+    def test_renew_form_date_too_far_in_future(self):
+        date = datetime.date.today() + datetime.timedelta(weeks=4) + datetime.timedelta(days=1)
+        form_data = {'renewal_date': date}
+        form = RenewBookForm(data=form_data)
+        self.assertFalse(form.is_valid())
+
+    def test_renew_form_date_today(self):
+        date = datetime.date.today()
+        form_data = {'renewal_date': date}
+        form = RenewBookForm(data=form_data)
+        self.assertTrue(form.is_valid())
+
+    def test_renew_form_date_max(self):
+        date = timezone.now() + datetime.timedelta(weeks=4)
+        form_data = {'renewal_date': date}
+        form = RenewBookForm(data=form_data)
+        self.assertTrue(form.is_valid())
+
+ +

The first two functions test that the field's label and help_text are as expected. We have to access the field using the fields dictionary (e.g. form.fields['renewal_date']). Note here that we also have to test whether the label value is None, because even though Django will render the correct label it returns None if the value is not explicitly set.

+ +

The rest of the functions test that the form is valid for renewal dates just inside the acceptable range and invalid for values outside the range. Note how we construct test date values around our current date (datetime.date.today()) using datetime.timedelta() (in this case specifying a number of days or weeks). We then just create the form, passing in our data, and test if it is valid.

+ +
+

Note: Here we don't actually use the database or test client. Consider modifying these tests to use SimpleTestCase.

+ +

We also need to validate that the correct errors are raised if the form is invalid, however this is usually done as part of view processing, so we'll take care of that in the next section.

+
+ +

That's all for forms; we do have some others, but they are automatically created by our generic class-based editing views, and should be tested there! Run the tests and confirm that our code still passes!

+ +

Views

+ +

To validate our view behaviour we use the Django test Client. This class acts like a dummy web browser that we can use to simulate GET and POST requests on a URL and observe the response. We can see almost everything about the response, from low-level HTTP (result headers and status codes) through to the template we're using to render the HTML and the context data we're passing to it. We can also see the chain of redirects (if any) and check the URL and status code at each step. This allows us to verify that each view is doing what is expected.

+ +

Let's start with one of our simplest views, which provides a list of all Authors. This is displayed at URL /catalog/authors/ (an URL named 'authors' in the URL configuration).

+ +
class AuthorListView(generic.ListView):
+    model = Author
+    paginate_by = 10
+
+ +

As this is a generic list view almost everything is done for us by Django. Arguably if you trust Django then the only thing you need to test is that the view is accessible at the correct URL and can be accessed using its name. However if you're using a test-driven development process you'll start by writing tests that confirm that the view displays all Authors, paginating them in lots of 10.

+ +

Open the /catalog/tests/test_views.py file and replace any existing text with the following test code for AuthorListView. As before we import our model and some useful classes. In the setUpTestData() method we set up a number of Author objects so that we can test our pagination.

+ +
from django.test import TestCase
+
+# Create your tests here.
+
+from catalog.models import Author
+from django.urls import reverse
+
+class AuthorListViewTest(TestCase):
+
+    @classmethod
+    def setUpTestData(cls):
+        #Create 13 authors for pagination tests
+        number_of_authors = 13
+        for author_num in range(number_of_authors):
+            Author.objects.create(first_name='Christian %s' % author_num, last_name = 'Surname %s' % author_num,)
+
+    def test_view_url_exists_at_desired_location(self):
+        resp = self.client.get('/catalog/authors/')
+        self.assertEqual(resp.status_code, 200)
+
+    def test_view_url_accessible_by_name(self):
+        resp = self.client.get(reverse('authors'))
+        self.assertEqual(resp.status_code, 200)
+
+    def test_view_uses_correct_template(self):
+        resp = self.client.get(reverse('authors'))
+        self.assertEqual(resp.status_code, 200)
+
+        self.assertTemplateUsed(resp, 'catalog/author_list.html')
+
+    def test_pagination_is_ten(self):
+        resp = self.client.get(reverse('authors'))
+        self.assertEqual(resp.status_code, 200)
+        self.assertTrue('is_paginated' in resp.context)
+        self.assertTrue(resp.context['is_paginated'] == True)
+        self.assertTrue( len(resp.context['author_list']) == 10)
+
+    def test_lists_all_authors(self):
+        #Get second page and confirm it has (exactly) remaining 3 items
+        resp = self.client.get(reverse('authors')+'?page=2')
+        self.assertEqual(resp.status_code, 200)
+        self.assertTrue('is_paginated' in resp.context)
+        self.assertTrue(resp.context['is_paginated'] == True)
+        self.assertTrue( len(resp.context['author_list']) == 3)
+ +

All the tests use the client (belonging to our TestCase's derived class) to simulate a GET request and get a response (resp). The first version checks a specific URL (note, just the specific path without the domain) while the second generates the URL from its name in the URL configuration.

+ +
resp = self.client.get('/catalog/authors/')
+resp = self.client.get(reverse('authors'))
+
+ +

Once we have the response we query it for its status code, the template used, whether or not the response is paginated, the number of items returned, and the total number of items.

+ +

The most interesting variable we demonstrate above is resp.context, which is the context variable passed to the template by the view. This is incredibly useful for testing, because it allows us to confirm that our template is getting all the data it needs. In other words we can check that we're using the intended template and what data the template is getting, which goes a long way to verifying that any rendering issues are solely due to template.

+ +

Views that are restricted to logged in users

+ +

In some cases you'll want to test a view that is restricted to just logged in users. For example our LoanedBooksByUserListView is very similar to our previous view but is only available to logged in users, and only displays BookInstance records that are borrowed by the current user, have the 'on loan' status, and are ordered "oldest first".

+ +
from django.contrib.auth.mixins import LoginRequiredMixin
+
+class LoanedBooksByUserListView(LoginRequiredMixin,generic.ListView):
+    """
+    Generic class-based view listing books on loan to current user.
+    """
+    model = BookInstance
+    template_name ='catalog/bookinstance_list_borrowed_user.html'
+    paginate_by = 10
+
+    def get_queryset(self):
+        return BookInstance.objects.filter(borrower=self.request.user).filter(status__exact='o').order_by('due_back')
+ +

Add the following test code to /catalog/tests/test_views.py. Here we first use SetUp() to create some user login accounts and BookInstance objects (along with their associated books and other records) that we'll use later in the tests. Half of the books are borrowed by each test user, but we've initially set the status of all books to "maintenance". We've used SetUp() rather than setUpTestData() because we'll be modifying some of these objects later.

+ +
+

Note: The setUp() code below creates a book with a specified Language, but your code may not include the Language model as this was created as a challenge. If this is the case, simply  comment out the parts of the code that create or import Language objects. You should also do this in the RenewBookInstancesViewTest section that follows.

+
+ +
import datetime
+from django.utils import timezone
+
+from catalog.models import BookInstance, Book, Genre, Language
+from django.contrib.auth.models import User #Required to assign User as a borrower
+
+class LoanedBookInstancesByUserListViewTest(TestCase):
+
+    def setUp(self):
+        #Create two users
+        test_user1 = User.objects.create_user(username='testuser1', password='12345')
+        test_user1.save()
+        test_user2 = User.objects.create_user(username='testuser2', password='12345')
+        test_user2.save()
+
+        #Create a book
+        test_author = Author.objects.create(first_name='John', last_name='Smith')
+        test_genre = Genre.objects.create(name='Fantasy')
+        test_language = Language.objects.create(name='English')
+        test_book = Book.objects.create(title='Book Title', summary = 'My book summary', isbn='ABCDEFG', author=test_author, language=test_language)
+        # Create genre as a post-step
+        genre_objects_for_book = Genre.objects.all()
+        test_book.genre.set(genre_objects_for_book) #Direct assignment of many-to-many types not allowed.
+        test_book.save()
+
+        #Create 30 BookInstance objects
+        number_of_book_copies = 30
+        for book_copy in range(number_of_book_copies):
+            return_date= timezone.now() + datetime.timedelta(days=book_copy%5)
+            if book_copy % 2:
+                the_borrower=test_user1
+            else:
+                the_borrower=test_user2
+            status='m'
+            BookInstance.objects.create(book=test_book,imprint='Unlikely Imprint, 2016', due_back=return_date, borrower=the_borrower, status=status)
+
+    def test_redirect_if_not_logged_in(self):
+        resp = self.client.get(reverse('my-borrowed'))
+        self.assertRedirects(resp, '/accounts/login/?next=/catalog/mybooks/')
+
+    def test_logged_in_uses_correct_template(self):
+        login = self.client.login(username='testuser1', password='12345')
+        resp = self.client.get(reverse('my-borrowed'))
+
+        #Check our user is logged in
+        self.assertEqual(str(resp.context['user']), 'testuser1')
+        #Check that we got a response "success"
+        self.assertEqual(resp.status_code, 200)
+
+        #Check we used correct template
+        self.assertTemplateUsed(resp, 'catalog/bookinstance_list_borrowed_user.html')
+
+ +

To verify that the view will redirect to a login page if the user is not logged in we use assertRedirects, as demonstrated in test_redirect_if_not_logged_in(). To verify that the page is displayed for a logged in user we first log in our test user, and then access the page again and check that we get a status_code of 200 (success). 

+ +

The rest of the tests verify that our view only returns books that are on loan to our current borrower. Copy the (self-explanatory) code at the end of the test class above.

+ +
    def test_only_borrowed_books_in_list(self):
+        login = self.client.login(username='testuser1', password='12345')
+        resp = self.client.get(reverse('my-borrowed'))
+
+        #Check our user is logged in
+        self.assertEqual(str(resp.context['user']), 'testuser1')
+        #Check that we got a response "success"
+        self.assertEqual(resp.status_code, 200)
+
+        #Check that initially we don't have any books in list (none on loan)
+        self.assertTrue('bookinstance_list' in resp.context)
+        self.assertEqual( len(resp.context['bookinstance_list']),0)
+
+        #Now change all books to be on loan
+        get_ten_books = BookInstance.objects.all()[:10]
+
+        for copy in get_ten_books:
+            copy.status='o'
+            copy.save()
+
+        #Check that now we have borrowed books in the list
+        resp = self.client.get(reverse('my-borrowed'))
+        #Check our user is logged in
+        self.assertEqual(str(resp.context['user']), 'testuser1')
+        #Check that we got a response "success"
+        self.assertEqual(resp.status_code, 200)
+
+        self.assertTrue('bookinstance_list' in resp.context)
+
+        #Confirm all books belong to testuser1 and are on loan
+        for bookitem in resp.context['bookinstance_list']:
+            self.assertEqual(resp.context['user'], bookitem.borrower)
+            self.assertEqual('o', bookitem.status)
+
+    def test_pages_ordered_by_due_date(self):
+
+        #Change all books to be on loan
+        for copy in BookInstance.objects.all():
+            copy.status='o'
+            copy.save()
+
+        login = self.client.login(username='testuser1', password='12345')
+        resp = self.client.get(reverse('my-borrowed'))
+
+        #Check our user is logged in
+        self.assertEqual(str(resp.context['user']), 'testuser1')
+        #Check that we got a response "success"
+        self.assertEqual(resp.status_code, 200)
+
+        #Confirm that of the items, only 10 are displayed due to pagination.
+        self.assertEqual( len(resp.context['bookinstance_list']),10)
+
+        last_date=0
+        for copy in resp.context['bookinstance_list']:
+            if last_date==0:
+                last_date=copy.due_back
+            else:
+                self.assertTrue(last_date <= copy.due_back)
+ +

You could also add pagination tests, should you so wish!

+ +

Testing views with forms

+ +

Testing views with forms is a little more complicated than in the cases above, because you need to test more code paths: initial display, display after data validation has failed, and display after validation has succeeded. The good news is that we use the client for testing in almost exactly the same way as we did for display-only views.

+ +

To demonstrate, let's write some tests for the view used to renew books (renew_book_librarian()):

+ +
from .forms import RenewBookForm
+
+@permission_required('catalog.can_mark_returned')
+def renew_book_librarian(request, pk):
+    """
+    View function for renewing a specific BookInstance by librarian
+    """
+    book_inst=get_object_or_404(BookInstance, pk = pk)
+
+    # If this is a POST request then process the Form data
+    if request.method == 'POST':
+
+        # Create a form instance and populate it with data from the request (binding):
+        form = RenewBookForm(request.POST)
+
+        # Check if the form is valid:
+        if form.is_valid():
+            # process the data in form.cleaned_data as required (here we just write it to the model due_back field)
+            book_inst.due_back = form.cleaned_data['renewal_date']
+            book_inst.save()
+
+            # redirect to a new URL:
+            return HttpResponseRedirect(reverse('all-borrowed') )
+
+    # If this is a GET (or any other method) create the default form
+    else:
+        proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3)
+        form = RenewBookForm(initial={'renewal_date': proposed_renewal_date,})
+
+    return render(request, 'catalog/book_renew_librarian.html', {'form': form, 'bookinst':book_inst})
+ +

We'll need to test that the view is only available to users who have the can_mark_returned permission, and that users are redirected to an HTTP 404 error page if they attempt to renew a BookInstance that does not exist. We should check that the initial value of the form is seeded with a date three weeks in the future, and that if validation succeeds we're redirected to the "all-borrowed books" view. As part of checking the validation-fail tests we'll also check that our form is sending the appropriate error messages.

+ +

Add the first part of the test class (shown below) to the bottom of /catalog/tests/test_views.py. This creates two users and two book instances, but only gives one user the permission required to access the view. The code to grant permissions during tests is shown in bold:

+ +
from django.contrib.auth.models import Permission # Required to grant the permission needed to set a book as returned.
+
+class RenewBookInstancesViewTest(TestCase):
+
+    def setUp(self):
+        #Create a user
+        test_user1 = User.objects.create_user(username='testuser1', password='12345')
+        test_user1.save()
+
+        test_user2 = User.objects.create_user(username='testuser2', password='12345')
+        test_user2.save()
+        permission = Permission.objects.get(name='Set book as returned')
+        test_user2.user_permissions.add(permission)
+        test_user2.save()
+
+        #Create a book
+        test_author = Author.objects.create(first_name='John', last_name='Smith')
+        test_genre = Genre.objects.create(name='Fantasy')
+        test_language = Language.objects.create(name='English')
+        test_book = Book.objects.create(title='Book Title', summary = 'My book summary', isbn='ABCDEFG', author=test_author, language=test_language,)
+        # Create genre as a post-step
+        genre_objects_for_book = Genre.objects.all()
+        test_book.genre.set(genre_objects_for_book) # Direct assignment of many-to-many types not allowed.
+        test_book.save()
+
+        #Create a BookInstance object for test_user1
+        return_date= datetime.date.today() + datetime.timedelta(days=5)
+        self.test_bookinstance1=BookInstance.objects.create(book=test_book,imprint='Unlikely Imprint, 2016', due_back=return_date, borrower=test_user1, status='o')
+
+        #Create a BookInstance object for test_user2
+        return_date= datetime.date.today() + datetime.timedelta(days=5)
+        self.test_bookinstance2=BookInstance.objects.create(book=test_book,imprint='Unlikely Imprint, 2016', due_back=return_date, borrower=test_user2, status='o')
+ +

Add the following tests to the bottom of the test class. These check that only users with the correct permissions (testuser2) can access the view. We check all the cases: when the user is not logged in, when a user is logged in but does not have the correct permissions, when the user has permissions but is not the borrower (should succeed), and what happens when they try to access a BookInstance that doesn't exist. We also check that the correct template is used.

+ +
    def test_redirect_if_not_logged_in(self):
+        resp = self.client.get(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}) )
+        #Manually check redirect (Can't use assertRedirect, because the redirect URL is unpredictable)
+        self.assertEqual( resp.status_code,302)
+        self.assertTrue( resp.url.startswith('/accounts/login/') )
+
+    def test_redirect_if_logged_in_but_not_correct_permission(self):
+        login = self.client.login(username='testuser1', password='12345')
+        resp = self.client.get(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}) )
+
+        #Manually check redirect (Can't use assertRedirect, because the redirect URL is unpredictable)
+        self.assertEqual( resp.status_code,302)
+        self.assertTrue( resp.url.startswith('/accounts/login/') )
+
+    def test_logged_in_with_permission_borrowed_book(self):
+        login = self.client.login(username='testuser2', password='12345')
+        resp = self.client.get(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance2.pk,}) )
+
+        #Check that it lets us login - this is our book and we have the right permissions.
+        self.assertEqual( resp.status_code,200)
+
+    def test_logged_in_with_permission_another_users_borrowed_book(self):
+        login = self.client.login(username='testuser2', password='12345')
+        resp = self.client.get(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}) )
+
+        #Check that it lets us login. We're a librarian, so we can view any users book
+        self.assertEqual( resp.status_code,200)
+
+    def test_HTTP404_for_invalid_book_if_logged_in(self):
+        import uuid
+        test_uid = uuid.uuid4() #unlikely UID to match our bookinstance!
+        login = self.client.login(username='testuser2', password='12345')
+        resp = self.client.get(reverse('renew-book-librarian', kwargs={'pk':test_uid,}) )
+        self.assertEqual( resp.status_code,404)
+
+    def test_uses_correct_template(self):
+        login = self.client.login(username='testuser2', password='12345')
+        resp = self.client.get(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}) )
+        self.assertEqual( resp.status_code,200)
+
+        #Check we used correct template
+        self.assertTemplateUsed(resp, 'catalog/book_renew_librarian.html')
+
+ +

Add the next test method, as shown below. This checks that the initial date for the form is three weeks in the future. Note how we are able to access the value of the initial value of the form field (shown in bold).

+ +
    def test_form_renewal_date_initially_has_date_three_weeks_in_future(self):
+        login = self.client.login(username='testuser2', password='12345')
+        resp = self.client.get(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}) )
+        self.assertEqual( resp.status_code,200)
+
+        date_3_weeks_in_future = datetime.date.today() + datetime.timedelta(weeks=3)
+        self.assertEqual(resp.context['form'].initial['renewal_date'], date_3_weeks_in_future )
+
+ +

The next test (add this to the class too) checks that the view redirects to a list of all borrowed books if renewal succeeds. What differs here is that for the first time we show how you can POST data using the client. The post data is the second argument to the post function, and is specified as a dictionary of key/values.

+ +
    def test_redirects_to_all_borrowed_book_list_on_success(self):
+        login = self.client.login(username='testuser2', password='12345')
+        valid_date_in_future = datetime.date.today() + datetime.timedelta(weeks=2)
+        resp = self.client.post(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}), {'renewal_date':valid_date_in_future} )
+        self.assertRedirects(resp, reverse('all-borrowed') )
+
+ +
+

The all-borrowed view was added as a challenge, and your code may instead redirect to the home page '/'. If so, modify the last two lines of the test code to be like the code below. The follow=True in the request ensures that the request returns the final destination URL (hence checking /catalog/ rather than /).

+ +
 resp = self.client.post(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}), {'renewal_date':valid_date_in_future},follow=True )
+ self.assertRedirects(resp, '/catalog/')
+
+ +

Copy the last two functions into the class, as seen below. These again test POST requests, but in this case with invalid renewal dates. We use assertFormError() to verify that the error messages are as expected.

+ +
    def test_form_invalid_renewal_date_past(self):
+        login = self.client.login(username='testuser2', password='12345')
+        date_in_past = datetime.date.today() - datetime.timedelta(weeks=1)
+        resp = self.client.post(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}), {'renewal_date':date_in_past} )
+        self.assertEqual( resp.status_code,200)
+        self.assertFormError(resp, 'form', 'renewal_date', 'Invalid date - renewal in past')
+
+    def test_form_invalid_renewal_date_future(self):
+        login = self.client.login(username='testuser2', password='12345')
+        invalid_date_in_future = datetime.date.today() + datetime.timedelta(weeks=5)
+        resp = self.client.post(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}), {'renewal_date':invalid_date_in_future} )
+        self.assertEqual( resp.status_code,200)
+        self.assertFormError(resp, 'form', 'renewal_date', 'Invalid date - renewal more than 4 weeks ahead')
+
+ +

The same sorts of techniques can be used to test the other view.

+ +

Templates

+ +

Django provides test APIs to check that the correct template is being called by your views, and to allow you to verify that the correct information is being sent. There is however no specific API support for testing in Django that your HTML output is rendered as expected.

+ + + +

Django's test framework can help you write effective unit and integration tests — we've only scratched the surface of what the underlying unittest framework can do, let alone Django's additions (for example, check out how you can use unittest.mock to patch third party libraries so you can more thoroughly test your own code).

+ +

While there are numerous other test tools that you can use, we'll just highlight two:

+ + + +

Challenge yourself

+ +

There are a lot more models and views we can test. As a simple task, try to create a test case for the AuthorCreate view.

+ +
class AuthorCreate(PermissionRequiredMixin, CreateView):
+    model = Author
+    fields = '__all__'
+    initial={'date_of_death':'12/10/2016',}
+    permission_required = 'catalog.can_mark_returned'
+ +

Remember that you need to check anything that you specify or that is part of the design. This will include who has access, the initial date, the template used, and where the view redirects on success.

+ +

Summary

+ +

Writing test code is neither fun nor glamorous, and is consequently often left to last (or not at all) when creating a website. It is however an essential part of making sure that your code is safe to release after making changes, and cost-effective to maintain.

+ +

In this tutorial we've shown you how to write and run tests for your models, forms, and views. Most importantly we've provided a brief summary of what you should test, which is often the hardest thing to work out when you're getting started. There is a lot more to know, but even with what you've learned already you should be able to create effective unit tests for your websites.

+ +

The next and final tutorial shows how you can deploy your wonderful (and fully tested!) Django website.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/Server-side/Django/Forms", "Learn/Server-side/Django/Deployment", "Learn/Server-side/Django")}}

+ +

 

+ +

In this module

+ + + +

 

diff --git a/files/zh-tw/learn/server-side/django/tutorial_local_library_website/index.html b/files/zh-tw/learn/server-side/django/tutorial_local_library_website/index.html new file mode 100644 index 0000000000..3e2cae3be5 --- /dev/null +++ b/files/zh-tw/learn/server-side/django/tutorial_local_library_website/index.html @@ -0,0 +1,92 @@ +--- +title: 'Django 教學 1: 本地圖書館網站' +slug: Learn/Server-side/Django/Tutorial_local_library_website +tags: + - django + - 初學者 +translation_of: Learn/Server-side/Django/Tutorial_local_library_website +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Django/development_environment", "Learn/Server-side/Django/skeleton_website", "Learn/Server-side/Django")}}
+ +

我們實戰教學系列的第一篇,會解釋你將學到什麼。並提供一個“本地圖書館” 的例子,作為概述。在接下來的教學裡,我們會不斷完善和改進這個網站。

+ + + + + + + + + + + + +
前提:閱讀 Django 介紹。在接下來的文章裡,你需要創建 Django 開發環境.
目標:介紹教學裡使用的網站應用,讓讀者明白要討論的主題。
+ +

概覽

+ +

歡迎來到 MDN 的 ”本地圖書館“ Django 教學。在教學裡,我們會開發一個網站,用來管理本地圖書館的目錄。

+ +

在這一系列的教學裡,你將:

+ + + +

關於這些主題,你已經學會了一些,並對其他的也有了簡單的了解。在這系列教學的最後,你會學到足夠多,而可以自己開發簡單的Django 應用了。

+ +

本地圖書館網站

+ +

本地圖書館,是我們在本系列教學裡,創建和不斷改善的網站。跟你期望的一樣,這個網站的目標,是為一個小型的圖書館,提供一個線上目錄。在這個小型圖書館裡,用戶能瀏覽書籍,和管理他們的帳號。

+ +

這個例子是精心挑選出來的,因為它可以根據我們的需要,增加或多或少的細節。也能用來展示,幾乎所有的 Django 特性。更重要的是,它提供了一條指南式的路線,在這條路線中,我們會用到 Django 網路框架最重要的功能:

+ + + +

儘管這是一個非常容易擴展的例子,它被稱為本地圖書館是有原因的——我們希望用最少的訊息,幫助你快速創建、和運用 Django。最後,我們會存儲圖書訊息,圖書數量,作者和其他重要訊息。我們不會儲存圖書館可能會儲存的其他訊息,或是提供一個支持多個圖書館、或是 ”大型圖書館“ 功能的建構。

+ +

我卡住了,從哪裡獲得源程式碼呢?

+ +

在學習本系列教程時,我們會提供合適的代碼片段,你可以粘貼複製,但是有些代碼我們希望你能自己擴展(在提示下)。

+ +

如果你卡在某個地方,你可以在 Github 裡找到網站的完整代碼。

+ +

總結

+ +

現在你對本地圖書館網站有了一些了解並知道你會學到什麼。是時候創建我們例子會用到的網站框架了。

+ +

{{PreviousMenuNext("Learn/Server-side/Django/development_environment", "Learn/Server-side/Django/skeleton_website", "Learn/Server-side/Django")}}

+ +

本系列教學

+ + diff --git a/files/zh-tw/learn/server-side/django/web_application_security/index.html b/files/zh-tw/learn/server-side/django/web_application_security/index.html new file mode 100644 index 0000000000..f644f400b9 --- /dev/null +++ b/files/zh-tw/learn/server-side/django/web_application_security/index.html @@ -0,0 +1,180 @@ +--- +title: Django web application security +slug: Learn/Server-side/Django/web_application_security +translation_of: Learn/Server-side/Django/web_application_security +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Django/Deployment", "Learn/Server-side/Django/django_assessment_blog", "Learn/Server-side/Django")}}
+ +

保護用戶數據是任何網站設計的重要部分。我們之前在文章 web 安全中,解釋了一些更常見的安全威脅 -- 本文提供了 Django 的內置保護如何處理這些威脅的實際演示。

+ + + + + + + + + + + + +
Prerequisites:Read the Server-side progamming "Website security" topic. Complete the Django tutorial topics up to (and including) at least Django Tutorial Part 9: Working with forms.
Objective:To understand the main things you need to do (or not do) to secure your Django web application.
+ +

Overview

+ +

The Website security topic provides an overview of what website security means for server-side design, and some of the more common threats that you may need to protect against. One of the key messages in that article is that almost all attacks are successful when the web application trusts data from the browser.

+ +
+

Important: The single most important lesson you can learn about website security is to never trust data from the browser. This includes GET request data in URL parameters, POST data, HTTP headers and cookies, user-uploaded files, etc. Always check and sanitize all incoming data. Always assume the worst.

+
+ +

The good news for Django users is that many of the more common threats are handled by the framework! The Security in Django (Django docs) article explains Django's security features and how to secure a Django-powered website.

+ +

Common threats/protections

+ +

Rather than duplicate the Django documentation here, in this article we'll demonstrate just a few of the security features in the context of our Django LocalLibrary tutorial.

+ +

Cross site scripting (XSS)

+ +

XSS is a term used to describe a class of attacks that allow an attacker to inject client-side scripts through the website into the browsers of other users. This is usually achieved by storing malicious scripts in the database where they can be retrieved and displayed to other users, or by getting users to click a link that will cause the attacker’s JavaScript to be executed by the user’s browser.

+ +

Django's template system protects you against the majority of XSS attacks by escaping specific characters that are "dangerous" in HTML. We can demonstrate this by attempting to inject some JavaScript into our LocalLibrary website using the Create-author form we set up in Django Tutorial Part 9: Working with forms.

+ +
    +
  1. Start the website using the development server (python3 manage.py runserver).
  2. +
  3. Open the site in your local browser and login to your superuser account.
  4. +
  5. Navigate to the author-creation page (which should be at URL: http://127.0.0.1:8000/catalog/author/create/).
  6. +
  7. Enter names and date details for a new user, and then append the following text to the Last Name field:
    + <script>alert('Test alert');</script>.
    + Author Form XSS test +
    +

    Note: This is a harmless script that, if executed, will display an alert box in your browser. If the alert is displayed when you submit the record then the site is vulnerable to XSS threats.

    +
    +
  8. +
  9. Press Submit to save the record.
  10. +
  11. When you save the author it will be displayed as shown below. Because of the XSS protections the alert() should not be run. Instead the script is displayed as plain text.Author detail view XSS test
  12. +
+ +

If you view the page HTML source code, you can see that the dangerous characters for the script tags have been turned into their harmless escape code equivalents (e.g. > is now &gt;)

+ +
<h1>Author: Boon&lt;script&gt;alert(&#39;Test alert&#39;);&lt;/script&gt;, David (Boonie) </h1>
+
+ +

Using Django templates protects you against the majority of XSS attacks. However it is possible to turn off this protection, and the protection isn't automatically applied to all tags that wouldn't normally be populated by user input (for example, the help_text in a form field is usually not user-supplied, so Django doesn't escape those values).

+ +

It is also possible for XSS attacks to originate from other untrusted source of data, such as cookies, Web services or uploaded files (whenever the data is not sufficiently sanitized before including in a page). If you're displaying data from these sources, then you may need to add your own sanitisation code.

+ +

Cross site request forgery (CSRF) protection

+ +

CSRF attacks allow a malicious user to execute actions using the credentials of another user without that user’s knowledge or consent. For example consider the case where we have a hacker who wants to create additional authors for our LocalLibrary.

+ +
+

Note: Obviously our hacker isn't in this for the money! A more ambitious hacker could use the same approach on other sites to perform much more harmful tasks (e.g. transfer money to their own accounts, etc.)

+
+ +

In order to do this, they might create an HTML file like the one below, which contains an author-creation form (like the one we used in the previous section) that is submitted as soon as the file is loaded. They would then send the file to all the Librarians and suggest that they open the file (it contains some harmless information, honest!). If the file is opened by any logged in librarian, then the form would be submitted with their credentials and a new author would be created.

+ +
<html>
+<body onload='document.EvilForm.submit()'>
+
+<form action="http://127.0.0.1:8000/catalog/author/create/" method="post" name='EvilForm'>
+  <table>
+    <tr><th><label for="id_first_name">First name:</label></th><td><input id="id_first_name" maxlength="100" name="first_name" type="text" value="Mad" required /></td></tr>
+    <tr><th><label for="id_last_name">Last name:</label></th><td><input id="id_last_name" maxlength="100" name="last_name" type="text" value="Man" required /></td></tr>
+    <tr><th><label for="id_date_of_birth">Date of birth:</label></th><td><input id="id_date_of_birth" name="date_of_birth" type="text" /></td></tr>
+    <tr><th><label for="id_date_of_death">Died:</label></th><td><input id="id_date_of_death" name="date_of_death" type="text" value="12/10/2016" /></td></tr>
+  </table>
+  <input type="submit" value="Submit" />
+</form>
+
+</body>
+</html>
+
+ +

Run the development web server, and log in with your superuser account. Copy the text above into a file and then open it in the browser. You should get a CSRF error, because Django has protection against this kind of thing!

+ +

The way the protection is enabled is that you include the {% csrf_token %} template tag in your form definition. This token is then rendered in your HTML as shown below, with a value that is specific to the user on the current browser.

+ +
<input type='hidden' name='csrfmiddlewaretoken' value='0QRWHnYVg776y2l66mcvZqp8alrv4lb8S8lZ4ZJUWGZFA5VHrVfL2mpH29YZ39PW' />
+
+ +

Django generates a user/browser specific key and will reject forms that do not contain the field, or that contain an incorrect field value for the user/browser.

+ +

To use this type of attack the hacker now has to discover and include the CSRF key for the specific target user. They also can't use the "scattergun" approach of sending a malicious file to all librarians and hoping that one of them will open it, since the CSRF key is browser specific.

+ +

Django's CSRF protection is turned on by default. You should always use the {% csrf_token %} template tag in your forms and use POST for requests that might change or add data to the database.

+ +

Other protections

+ +

Django also provides other forms of protection (most of which would be hard or not particularly useful to demonstrate):

+ +
+
SQL injection protection
+
SQL injection vulnerabilities enable malicious users to execute arbitrary SQL code on a database, allowing data to be accessed, modified, or deleted irrespective of the user's permissions. In almost every case you'll be accessing the database using Django’s querysets/models, so the resulting SQL will be properly escaped by the underlying database driver. If you do need to write raw queries or custom SQL then you'll need to explicitly think about preventing SQL injection.
+
Clickjacking protection
+
In this attack a malicious user hijacks clicks meant for a visible top level site and routes them to a hidden page beneath. This technique might be used, for example, to display a legitimate bank site but capture the login credentials in an invisible <iframe> controlled by the attacker. Django contains clickjacking protection in the form of the X-Frame-Options middleware which, in a supporting browser, can prevent a site from being rendered inside a frame.
+
Enforcing SSL/HTTPS
+
SSL/HTTPS can be enabled on the web server in order to encrypt all traffic between the site and browser, including authentication credentials that would otherwise be sent in plain text (enabling HTTPS is highly recommended). If HTTPS is enabled then Django provides a number of other protections you can use:
+
+ + + +
+
Host header validation
+
Use ALLOWED_HOSTS to only accept requests from trusted hosts.
+
+ +

There are many other protections, and caveats to the usage of the above mechanisms. While we hope that this has given you an overview of what Django offers, you should still read the Django security documentation.

+ + + +

Summary

+ +

Django has effective protections against a number of common threats, including XSS and CSRF attacks. In this article we've demonstrated how those particular threats are handled by Django in our LocalLibrary website. We've also provided a brief overview of some of the other protections.

+ +

This has been a very brief foray into web security. We strongly recommend that you read Security in Django to gain a deeper understanding.

+ +

The next and final step in this module about Django is to complete the assessment task.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/Server-side/Django/Deployment", "Learn/Server-side/Django/django_assessment_blog", "Learn/Server-side/Django")}}

+ +

 

+ +

In this module

+ + + +

 

diff --git a/files/zh-tw/learn/server-side/express_nodejs/deployment/index.html b/files/zh-tw/learn/server-side/express_nodejs/deployment/index.html new file mode 100644 index 0000000000..d7c2089cd1 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/deployment/index.html @@ -0,0 +1,521 @@ +--- +title: 'Express 教學 7: 佈署到生產環境' +slug: Learn/Server-side/Express_Nodejs/deployment +translation_of: Learn/Server-side/Express_Nodejs/deployment +--- +
{{LearnSidebar}}
+ +
{{PreviousMenu("Learn/Server-side/Express_Nodejs/forms", "Learn/Server-side/Express_Nodejs")}}
+ +

現在你已經創建(並測試)了一個不錯的 本地圖書館 網站了,你打算把它發佈到一個公共網絡服務器,這樣圖書館管理員和網路上的其他成員就可以訪問它了。這篇文章總結了你可以怎樣找到一台主機部署你的網站,以及你需要為網站準備好佈署到生產環境該做什麼。

+ + + + + + + + + + + + +
預備知識:完成前面所有的指南主題,包括 Express Tutorial Part 6: Working with forms.
目標:學習你可以怎樣以及在哪裡部署一個 Express 應用到生產環境。
+ +

概覽

+ +

一旦您的站點完成(或完成 “足夠” 以開始公共測試),您將需要將其託管在比您的個人開發計算機,更公開和可訪問的地方。

+ +

到目前為止,您一直在開發環境中工作,使用Express / Node 作為 Web 服務器,將您的站點共享到本地瀏覽器/網路,並使用(不安全的)開發設置運行您的網站,以顯示調試和其他私人信息。在您可以在外部託管網站之前,您首先必須:

+ + + +

本教程提供了,有關選擇託管站點的選項的一些指導,簡要概述了為使您的Express 應用程序準備好生產,所需執行的操作,以及一個工作示例,演示如何將 LocalLibrary 網站安裝到 Heroku 雲託管上的服務。

+ +

請記住,您不必使用 Heroku - 還有其他託管服務可用。我們還提供了一個單獨的教程,以展示如何在 PWS/Cloud Foundry 上安裝 LocalLibrary。

+ +

什麼是生產環境?

+ +

生產環境是服務器計算機提供的環境,您可以在其中運行網站,以供外部使用。環境包括:

+ + + +

服務器計算機,可以位於您的場所,並通過快速鏈接,連接到 Internet,但使用 “託管在雲上” 的計算機更為常見。這實際上意味著,您的代碼運行在託管公司的數據中心的某台遠程計算機(或可能是“虛擬”計算機)。遠程服務器,通常會以特定價格提供互聯網連接,和一些保證級別的計算資源(例如CPU,RAM,存儲器等)。

+ +

這種可遠程訪問的計算/網絡硬件,稱為基礎架構即服務(IaaS)。許多 IaaS 供應商,提供預安裝特定操作系統的選項,您必須在其上,安裝生產環境的其他組件。其他供應商,允許您選擇功能更全面的環境,可能包括完整的 node 設置。

+ +
+

注意: 預構建環境,可以使您的網站設置變得非常簡單,因為它們會減少配置,但可用選項可能會限制您使用不熟悉的服務器(或其他組件),並且可能基於較舊版本的操作系統。通常最好自己安裝組件,以便獲得所需的組件,並且當您需要升級系統的某些部分時,您可以知道從哪裡開始!

+
+ +

其他託管服務提供商,支持 Express 作為平台即服務(PaaS)產品的一部分。使用此類託管時,您無需擔心大多數生產環境(服務器,負載平衡器等),因為主機平台會為您處理這些問題。這使得部署非常簡單,因為您只需要專注於 Web 應用程序,而不是任何其他服務器基礎結構。

+ +

一些開發人員選擇 IaaS ,相對於 PaaS ,IaaS 提供更高靈活性,而其他開發人員偏好 PaaS 的降低維護開銷,和更輕鬆的擴展性。當您在一開始使用時,在 PaaS 系統上設置您的網站,要容易得多,因此我們將在本教程中使用 PaaS。

+ +
+

提示: 如果您選擇 Node/Express 友好的託管服務提供商,他們應該提供,有關如何使用 Web 服務器,應用程序服務器,反向代理等不同配置,來設置 Express 網站的說明。例如,在 Digital Ocean 的node 社區文檔中,有許多各種配置的手把手指南。

+
+ +

選擇一個主機供應商

+ +

眾所周知,眾多託管服務提供商,都積極支持或與 Node(和Express)合作。這些供應商提供不同類型的環境(IaaS,PaaS),以及不同價格的不同級別的計算和網絡資源。

+ +
+

提示: 有很多託管解決方案,他們的服務和定價,可能會隨著時間而改變。雖然我們在下面介紹幾個選項,但在選擇託管服務提供商之前,有必要自己進行互聯網搜索。

+
+ +

選擇主機時需要考慮的一些事項:

+ + + +

當你剛開始時,好消息是有很多網站提供“免費”的計算環境,儘管有一些條件。例如, Heroku  “永遠” 提供免費但資源有限的 PaaS 環境,而 Amazon Web Services, Microsoft Azure 和開源選項 PWS/Cloud Foundry 在您第一次加入時,提供免費信用額度。

+ +

許多提供商還擁有“基本”層,可提供更多有用的計算能力,和更少的限制。舉例來說, Digital Ocean 是一個流行的託管服務提供商,它提供了一個相對便宜的基本計算層(在本教程寫作時,是每月5美元的較低範圍)。

+ +
+

注意: 請記住,價格不是唯一的選擇標準。如果您的網站成功,可能會發現可擴展性是最重要的考慮因素。

+
+ +

準備好發布你的網站

+ +

發佈網站時,要考慮的主要問題是網絡安全性和性能。至少,您需要刪除開發期間,錯誤頁面上包含的堆棧跟踪,整理日誌記錄,並設置適當的標頭,以避免許多常見的安全威脅。

+ +

在以下小節中,我們概述了您應該對應用進行的、最重要的更改。

+ +
+

提示: Express文檔中還有其他有用的提示 - 請參閱“生產最佳實踐:性能和可靠性”,以及“生產最佳實踐:安全性”。

+
+ +

設置 NODE_ENV 為 'production'

+ +

我們可以通過將 NODE_ENV 環境變量,設置為 production ,來刪除錯誤頁面中的堆棧跟踪(默認設置為 “development” )。除了生成較為不詳細的錯誤消息之外,還要將變量設置為生產緩存視圖模板,和從 CSS 擴展生成的 CSS 文件。測試表明,將NODE_ENV設置為生產,可以將應用程序性能提高三倍!

+ +

可以使用導出或環境文件,或使用 OS 初始化系統,以進行此更改。

+ +
+

注意: 這實際上是在環境設置,而不是應用中所做的更改,但重要的是,要注意這裡!我們將在下面,展示我們的託管示例要如何設置。

+
+ +

Log appropriately

+ +

記錄呼叫會對高流量網站產生影響。在生產環境中,您可能需要記錄網站活動(例如,跟踪流量,或記錄API調用),但您應嘗試最小化為調試目的而添加的日誌記錄量。

+ +

在生產環境中,最小化“調試”日誌記錄的一種方法,是使用類似調試 debug  的模塊,允許您通過設置環境變量,來控制執行的日誌記錄。例如,下面的代碼片段,顯示如何設置 “author” 日誌記錄。調試變量使用名稱 “author” 聲明,並且將自動顯示,來自此對象的所有日誌的前綴 “author”。

+ +
var debug = require('debug')('author');
+
+// Display Author update form on GET
+exports.author_update_get = function(req, res, next) {
+
+    req.sanitize('id').escape().trim();
+    Author.findById(req.params.id, function(err, author) {
+        if (err) {
+            debug('update error:' + err);
+            return next(err);
+        }
+        //On success
+        res.render('author_form', { title: 'Update Author', author: author });
+    });
+
+};
+ +

然後,您可以通過在 DEBUG 環境變量中,將它們指定為逗號分隔列表,來啟用特定日誌集。您可以設置顯示作者和書籍日誌的變量,如圖所示(也支持通配符)。

+ +
#Windows
+set DEBUG=author,book
+
+#Linux
+export DEBUG="author,book"
+
+ +
+

挑戰: 調用debug可以替換您以前使用 console.log()console.error()執行的日誌記錄。通過調試模塊 debug 進行日誌記錄,替換代碼中的所有console.log()調用。通過設置 DEBUG 變量,並在其中記錄對日誌記錄的影響,在開發環境中,打開和關閉日誌記錄。

+
+ +

如果您需要記錄網站活動,可以使用 Winston 或 Bunyan 等日誌庫。有關此主題的更多信息,請參閱:生產最佳實踐:性能和可靠性

+ +

使用 gzip/deflate 壓縮響應

+ +

Web 服務器,通常可以壓縮發送回客戶端的 HTTP 響應,從而顯著減少客戶端獲取和加載頁面所需的時間。使用的壓縮方法,取決於客戶端在請求中支持的解壓縮方法(如果不支持壓縮方法,則響應將以未壓縮的方式發送)。

+ +

您可以使用壓縮中間件 compression,將其添加到您的站點。通過在項目的根目錄下,運行以下命令,將其安裝到項目中。

+ +
npm install compression
+ +

打開./app.js,並導入壓縮庫,如圖所示。使用 use()方法,將壓縮庫添加到中間件鏈(這應該出現在您想要壓縮的任何路由之前 - 在本教程這種情況下,全部都是!)

+ +
var catalogRouter = require('./routes/catalog'); //Import routes for "catalog" area of site
+var compression = require('compression');
+
+// Create the Express application object
+var app = express();
+
+...
+
+app.use(compression()); //Compress all routes
+
+app.use(express.static(path.join(__dirname, 'public')));
+
+app.use('/', indexRouter);
+app.use('/users', usersRouter);
+app.use('/catalog', catalogRouter);  // Add catalog routes to middleware chain.
+
+...
+
+ +
+

注意: 對於生產中流量較大的網站,您不會使用此中間件。相反,你會使用像 Nginx 這樣的反向代理。

+
+ +

使用 Helmet 避免被常見漏洞侵襲

+ +

Helmet 是一個中間件包,可以通過設置適當的 HTTP 標頭,來幫助保護您的應用,免受一些眾所周知的 Web 漏洞的影響(有關它設置的標頭/防護漏洞的詳細信息,請參閱文檔 docs) 。

+ +

通過在項目的根目錄下,運行以下命令,將其安裝到項目中。

+ +
npm install helmet
+
+ +

打開./app.js,並導入如圖所示的 helmet 庫。然後使用use()方法,將模塊添加到中間件鏈。

+ +
var compression = require('compression');
+var helmet = require('helmet');
+
+// Create the Express application object
+var app = express();
+
+app.use(helmet());
+...
+ +
+

注意: 上面的命令,添加了對大多數站點有意義的可用標頭子集。您可以按照 npm 上的說明,根據需要添加/禁用特定標頭。

+
+ +

例子:在 Heroku 上安裝本地圖書館

+ +

本節提供如何在 Heroku PaaS cloud 雲上安裝 LocalLibrary 的實際演示。

+ +

為什麼選擇 Heroku?

+ +

Heroku 是運行時間最長,且最受歡迎的基於雲的 PaaS 服務之一。它最初只支持 Ruby 應用程序,但現在可用於託管來自許多編程環境的應用程序,包括 Node(以及Express)!

+ +

我們選擇使用 Heroku 有以下幾個原因:

+ + + +

雖然 Heroku 非常適合舉辦此演示,但它可能並不適合您的真實網站。 Heroku 可以輕鬆設置和擴展,但代價是靈活性較低,而且一旦退​​​​出免費套餐,可能會花費更多。

+ +

Heroku 如何工作?

+ +

Heroku在一個或多個 "Dynos" 中運行網站,這些 “Dynos” 是獨立的虛擬化Unix容器,提供運行應用程序所需的環境。 Dynos 是完全隔離的,並且有一個短暫的文件系統(一個短暫的文件系統,每次dyno重新啟動時都會清理/清空)。 dynos 默認共享的唯一內容,是應用程序配置變量 configuration variables。 Heroku 內部使用負載均衡器,將Web流量分配給所有 “web” dynos。由於它們之間沒有任何共享,Heroku 可以通過添加更多 dynos,來水平擴展應用程序(當然,您可能還需要擴展數據庫,以接受其他連接)。

+ +

由於文件系統是短暫的,因此無法直接安裝應用程序所需的服務(例如數據庫,隊列,緩存系統,存儲,電子郵件服務等)。相反,Heroku Web應用程序使用 Heroku 或第三方作為獨立“附加組件”提供的支持服務。連接到Web應用程序後,可以通過環境變量,在Web應用程序中訪問附加服務。

+ +

為了執行您的應用程序,Heroku 需要能夠設置適當的環境和依賴關係,並了解它是如何啟動的。對於 Node 應用程序,它所需的所有信息都是從 package.json文件中獲取的。

+ +

開發人員使用特殊的客戶端應用程序/終端,與 Heroku 交互,這很像 Unix bash 腳本。這允許您上傳存儲在 git 儲存庫中的代碼,檢查正在運行的進程,查看日誌,設置配置變量等等!

+ +

為了讓我們的應用程序在 Heroku 上工作,我們需要將我們的 Express Web 應用程序放入 git 儲存庫,並對 package.json 進行一些小的更改。完成後,我們可以設置Heroku 帳戶,獲取 Heroku 客戶端,並使用它來安裝我們的網站。

+ +

這是您開始教程所需的全部概述(有關更全面的指南,請參閱帶有 Node.js 的Heroku 入門)。

+ +

在 Github 上創建一個應用倉庫

+ +

Heroku 與 git 源代碼版本控制系統緊密集成,使用它來上傳/同步您對實時運行系統所做的任何更改。它通過添加一個名為 heroku 的新 Heroku“遠程”儲存庫,來指向您在Heroku雲上的源儲存庫。在開發期間,您使用 git 在“主”儲存庫 master 中儲存更改。如果要部署站點,請將更改同步到 Heroku 存儲庫。

+ +
+

注意: 如果您習慣於遵循良好的軟件開發實踐,那麼您可能已經在使用 git 或其他一些 SCM 系統。如果您已有 git 儲存庫,則可以跳過此步驟。

+
+ +

有很多方法可以使用git,但最簡單的方法之一,是首先在 GitHub 上建立一個帳戶,在那裡創建儲存庫,然後在本地同步它:

+ +
    +
  1. 訪問 https://github.com/ 並創建一個帳戶。
  2. +
  3. 登錄後,單擊頂部工具欄中的 + 號鏈接,然後選擇新建儲存庫  New repository
  4. +
  5. 填寫此表單上的所有字段。雖然這些不是強制性的,但強烈建議使用它們。 +
      +
    • 輸入新的存儲庫名稱(例如,express-locallibrary-tutorial)和描述(例如 “以Express(node)編寫的本地圖書館網站”)。
    • +
    • 在 Add .gitignore 選擇列表中選擇 Node
    • +
    • 在添加許可證 Add license 選擇列表中,選擇您偏好的許可證。
    • +
    • 點選 使用自述文件初始化此儲存庫 Initialize this repository with a README.
    • +
    +
  6. +
  7. Create repository.
  8. +
  9. 單擊新倉庫頁面上的綠色“克隆或下載”按鈕 "Clone or download" 。
  10. +
  11. 從顯示的對話框的文本字段,複製 URL值(它應該類似於:https://github.com/<your_git_user_id>/express-locallibrary-tutorial.git)。
  12. +
+ +

現在創建了儲存庫(“repo”),我們將要在本地計算機上克隆它:

+ +
    +
  1. 為您的本地計算機安裝 git(您可以在此處找到不同平台的版本)。
    +  
  2. +
  3. 打開命令提示符/終端,並使用您在上面複製的 URL ,克隆儲存庫: +
    git clone https://github.com/<your_git_user_id>/express-locallibrary-tutorial.git
    +
    + 這將在當前時間點之後,創建儲存庫。
  4. +
  5. 到新的儲存庫。 +
    cd express-locallibrary-tutorial
    +
  6. +
+ +

最後一步,是複制你的應用程序,然後使用 git ,將文件添加到你的倉庫:

+ +
    +
  1. 將Express應用程序,複製到此文件夾中(不包括 /node_modules,其中包含您應根據需要,從 NPM 獲取的依賴項文件)。
  2. +
  3. 打開命令提示符/終端,並使用 add 命令,將所有文件添加到 git。
  4. +
  5. +
    git add -A
    +
    +
  6. +
  7. 使用 status 命令,檢查要添加的所有文件是否正確(您希望包含源文件,而不是二進製文件,臨時文件等)。它應該看起來有點像下面的列表。 +
    > git status
    +On branch master
    +Your branch is up-to-date with 'origin/master'.
    +Changes to be committed:
    +  (use "git reset HEAD <file>..." to unstage)
    +
    +        new file:   ...
    +
  8. +
  9. 如果您滿意,請將文件提交到本地儲存庫: +
    git commit -m "First version of application moved into github"
    +
  10. +
  11. 然後使用以下內容,將本地儲存庫同步到 Github 網站: +
    git push origin master
    +
  12. +
+ +

完成此操作後,您應該可以返回創建儲存庫的 Github 上的頁面,刷新頁面,並查看您的整個應用程序現已上傳。使用此添加/提交/推送循環,您可以在文件更改時,繼續更新儲存庫。

+ +
+

提示: 這是備份你的“vanilla”項目的好時機 - 雖然我們將在以下部分中進行的一些更改,可能對任何平台(或開發)上的部署有用,而一些其他的更改可能沒有用。

+ +

執行此操作的最佳方法,是使用 git 來管理您的修訂。使用 git,您不僅可以回到特定的舊版本,而且可以在生產變更的單獨“分支”中進行維護,並選擇在生產和開發分支之間移動的任何更改。學習Git非常值得,但超出了本主題的範圍。

+ +

最簡單的方法,是將文件複製到另一個位置。以您對 git 了解,使用最符合的方法!

+
+ +

更新 Heroku 的應用程序

+ +

本節介紹了您需要對 LocalLibrary 應用程序進行的更改,以使其在 Heroku 上運行。

+ +

設置 node 版本

+ +

package.json 包含解決應用程序依賴項所需的所有內容,以及啟動站點時,應啟動的文件。 Heroku 檢測到此文件的存在,並將使用它來配置您的應用程序環境。

+ +

我們當前的 package.json 中,缺少的唯一有用信息,是 node 的版本。我們可以通過輸入命令,找到我們用於開發的 node 版本:

+ +
>node --version
+v8.9.1
+ +

打開 package.json,並將此信息添加為 engines > node 部分,如圖所示(使用系統的版本號)。

+ +
{
+  "name": "express-locallibrary-tutorial",
+  "version": "0.0.0",
+  "engines": {
+    "node": "8.9.1"
+  },
+  "private": true,
+  ...
+
+ +

數據庫配置

+ +

到目前為止,在本教程中,我們使用了一個硬編碼到 app.js 的單個數據庫。通常我們希望,能夠為生產和開發創建不同的數據庫,接下來我們將修改 LocalLibrary 網站,以從 OS 環境獲取數據庫 URI(如果已定義),否則使用我們的開發數據庫。

+ +

打開 app.js,並找到設置 mongoDB 連接變量的行。它看起來像這樣:

+ +
var mongoDB = 'mongodb://your_user_id:your_password@ds119748.mlab.com:19748/local_library';
+ +

使用以下代碼替換該行,該代碼使用 process.env.MONGODB_URI 從名為 MONGODB_URI 的環境變量中,獲取連接字符串(如果已設置)(使用您自己的數據庫URL,而不是下面的佔位符。)

+ +
var mongoDB = process.env.MONGODB_URI || 'mongodb://your_user_id:your_password@ds119748.mlab.com:19748/local_library';
+
+ +

安裝依賴並重新測試

+ +

在我們繼續之前,讓我們再次測試該網站,並確保它不受我們的任何更改的影響。

+ +

首先,我們需要獲取我們的依賴項(你會記得,我們​​沒有將 node_modules文件夾,複製到我們的 git 樹中)。您可以通過在項目根目錄的終端中,運行以下命令來執行此操作:

+ +
npm install
+
+ +

現在運行該站點(請參閱測試路由的相關命令),並檢查該站點,是否仍按預期運行。

+ +

將更改保存到 Github

+ +

接下來,讓我們將所有更改保存到 Github。在終端中(在我們的儲存庫中),輸入以下命令:

+ +
git add -A
+git commit -m "Added files and changes required for deployment to heroku"
+git push origin master
+ +

我們現在應該準備開始在 Heroku 上,部署 LocalLibrary。

+ +

獲取一個 Heroku 帳戶

+ +

要開始使用 Heroku,您首先需要創建一個帳戶(如果您已經擁有一個帳戶,並安裝了 Heroku 客戶端,請跳過創建並上傳網站):

+ + + +

安裝客戶端

+ +

按照 Heroku 上的說明,下載並安裝 Heroku 客戶端。

+ +

安裝客戶端后,您將能夠運行命令。例如,要獲得客戶端的幫助說明:

+ +
heroku help
+
+ +

創建並上傳網站

+ +

要創建應用程序,我們在儲存庫的根目錄中,運行 “create” 命令。這將在我們的本地git 環境中,創建一個名為 heroku 的 git remote(“指向遠程儲存庫的指針”)。

+ +
heroku create
+ +
+

注意: 如果您願意,可以在“創建”create 之後指定遠程儲存庫的命名。如果你不這樣做,你會得到一個隨機的名字。該名稱用於默認 URL。

+
+ +

然後,我們可以將我們的應用程序,推送到 Heroku 儲存庫,如下所示。這將上傳應用程序,獲取所有依賴項,將其打包到 dyno 中,然後啟動該站點。

+ +
git push heroku master
+ +

如果我們很幸運,該應用程序現在正在網站上“運行”。要打開瀏覽器並運行新網站,請使用以下命令:

+ +
heroku open
+ +
+

注意: 該站點將使用我們的開發數據庫運行。創建一些書本和其他對象,並檢查該網站是否按預期運行。在下一節中,我們將其設置為使用我們的新數據庫。

+
+ +

設定配置變量

+ +

您將從前一節回憶起,我們需要將 NODE_ENV 設置為 'production',以便提高性能,並生成更簡潔的錯誤消息。我們通過輸入以下命令,來完成此操作:

+ +
>heroku config:set NODE_ENV='production'
+Setting NODE_ENV and restarting limitless-tor-18923... done, v13
+NODE_ENV: production
+
+ +

我們還應該使用單獨的數據庫進行生產,在MONGODB_URI環境變量中,設置其URI。您可以完全按照我們原來的方式,設置新數據庫和數據庫用戶,並獲取其URI。您可以如下圖所示設置URI(顯然,要使用您自己的URI!)

+ +
>heroku config:set MONGODB_URI='mongodb://your_user:your_password@ds139278.mlab.com:39278/local_library_production'
+Setting MONGODB_URI and restarting limitless-tor-18923... done, v13
+MONGODB_URI: mongodb://your_user:your_password@ds139278.mlab.com:39278/local_library_production
+
+ +

您可以使用 heroku config 命令,隨時檢查配置變量 - 立即嘗試:

+ +
>heroku config
+=== limitless-tor-18923 Config Vars
+MONGODB_URI: mongodb://your_user:your_password@ds139278.mlab.com:39278/local_library_production
+NODE_ENV:    production
+
+ +

Heroku 會在更新變量時,重新啟動應用程序。如果您現在檢查主頁,它應該顯示對象計數的零值,因為上面的更改,意味著我們現在正在使用新的(空)數據庫。

+ +

管理附加組件

+ +

Heroku 使用獨立的附加組件,為應用程序提供支持服務 - 例如電子郵件或數據庫服務。我們不在本網站中使用任何插件,但它們是使用 Heroku 的重要部分,因此您可能需要查看主題 - 管理插件(Heroku 官方文件)

+ +

除錯

+ +

Heroku 客戶端提供了一些除錯工具:

+ +
heroku logs  # Show current logs
+heroku logs --tail # Show current logs and keep updating with any new results
+heroku ps   #Display dyno status
+
+ + + +

總結

+ +

本教程介紹在生產環境中,如何配置 Express 應用。是Express系列教程的最後一個。我們希望你覺得這些教程有用。你可以在 Github 上取得完整的源碼。

+ +

相關鏈接

+ + + +

{{PreviousMenu("Learn/Server-side/Express_Nodejs/forms", "Learn/Server-side/Express_Nodejs")}}

+ +

 

+ +

本教學鏈接

+ + + +

 

diff --git a/files/zh-tw/learn/server-side/express_nodejs/development_environment/index.html b/files/zh-tw/learn/server-side/express_nodejs/development_environment/index.html new file mode 100644 index 0000000000..3e556ada3a --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/development_environment/index.html @@ -0,0 +1,385 @@ +--- +title: Setting up a Node development environment +slug: Learn/Server-side/Express_Nodejs/development_environment +translation_of: Learn/Server-side/Express_Nodejs/development_environment +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Introduction", "Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs")}}
+ +

現在你已經了解Express的目的了,接下來繼續說明如何設定和測試 Windows、Linux (Ubuntu)和Mac OS X上的Node/Express開發環境。不管你用的是什麼作業系統,你都能在本文中找到開發Express應用的入門需知。

+ + + + + + + + + + + + +
前置需求:了解如何開啟terminal / command line. 了解如何在開發系統上安裝套件。
目標:在你的電腦上設定Express(X.XX)開發環境。
+ +

Express 開發環境概覽

+ +

為了使你能快速的開發web應用,Node 和 Express 非常容易安裝,這個部分說明哪些工具是需要的、在Ubuntu、macOS和Windows中安裝Node和Express的最簡單方法、展示如何測試安裝成功與否。

+ +

什麼是Express開發環境?

+ +

Express 開發環境包含 Nodejs、NPM 套件管理器的安裝, 還有 Express Application 產生器(可選)

+ +

Node 和 NPM 套件管理器會從準備好的 binary package、安裝檔、 作業系統的套件管理器或是從源檔一起安裝。接著 Express 會透過 NPM 進行安裝,成為你所有個別 Express web 應用的依賴項(以及其他函式庫,如模板引擎,資料庫驅動程式,身份驗證中間層,用於提供靜態文件的中間件等)

+ +

NPM 也可用來安裝 Express 應用程式產生器(全域用),一個方便的工具幫助你創造符合 MVC模式的 Express web app 骨架。你不一定要使用應用程式產生器,因為每個Express應用程式不需要擁有同樣的檔案結構或依賴項。但為了專注於學習本身以及習慣模組化架構,我們會在接下來的教學中使用它。

+ +
+

注意: 與其他不包含單獨的web開發伺服器的Web框架不同。 在Node / Express中,Web應用程式創建並運行自己的Web伺服器!

+
+ +

典型的開發環境還包含其他工具,例如:編輯程式碼使用的文字編輯器、IDE,進行版本控置管理不同版本程式碼的Git。這邊假設你已經有這種工具了(尤其是文字編輯器)

+ +

哪些作業系統有支援?

+ +

Node 可以執行在 Windows、macOS、各種 Linux、Docker 等等(nodejs 的下載頁面有完整的列表),在開發階段中個人電腦應該都有足夠的效能來執行 Node 。Express 執行在 Node 環境中,所以也能所有有安裝Node的平台上執行。

+ +

在這份教學中我們提供 Windows、macOS 和 Ubuntu Linux 的 Node 安裝教學。

+ +

該用什麼版本的 Node/Express?

+ +

Node 有許多版本,更新的版本代表著 bug 的修復、支援更新版本的 ECMAScript(JavaScript)標準和更好的 Node APIs 。

+ +

基本上你應該使用最新的 LTS 版本(long-term supported,長期維護版)。這種版本比『Current』版本更穩定而且還擁有最新的功能及持續性的更新維護。除非LTS不支援你需要的功能才使用『Current』版本。

+ +

而 Express ?永遠使用最新版!

+ +

關於資料庫和其他依賴項呢?

+ +

諸如資料庫、模版引擎、驗證引擎等等都屬於應用程式的一部分,這些依賴項會透過NPM導入應用程式環境中,在後續的章節將會進一步探討。

+ +

安裝Node

+ +

為了使用Express,首先要在你的電腦上安裝Node和Node Package Manager (NPM)。接下來用最簡單的方法在 Ubuntu Linux 16.04、 macOS和 Windows 10上安裝Nodejs的 Long Term Supported (LTS)版本吧

+ +
+

以下的部分用最簡單的方法在上述的作業系統中安裝Node和NPM。如果你使用其他作業系統或想看看其他平台的安裝方式,請查閱透過套件管理器安裝Node.js (nodejs.org)。

+
+ +

Windows 和macOS

+ +

直接使用安裝檔吧!

+ +
    +
  1. 下載需要的安裝檔: +
      +
    1. 開啟 https://nodejs.org/en/
    2. +
    3. 對於大部分的使用者來說,直接下載LTS版本
    4. +
    +
  2. +
  3. 下載完成後雙擊安裝檔,並照著安裝流程繼續。
  4. +
+ +

Ubuntu 16.04

+ +

安裝Node 8.x LTS版本最簡單的方法是使用套件管理器,只要在terminal上執行兩行指令

+ +
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
+sudo apt-get install -y nodejs
+
+
+ +
+

警告: 不要直接從普通的Ubuntu repositories 安裝,那邊只有很舊的版本。

+
+ +
    +
+ +

測試 Nodejs 和NPM 的安裝

+ +

測試Node安裝最簡單的方法是在terminal/command上執行"version"這個指令,它會顯示當前的Node版本:

+ +
>node -v
+v8.9.4
+ +

NPM應該會隨著Node一起安裝,可以用相同的方法進行測試:

+ +
>npm -v
+5.6.0
+ +

接著用稍為令人興奮的方法來測試吧!讓我們創件一個非常基本的『純Node』伺服器,當你開啟正確的網頁時它會在瀏覽器上顯示"Hello World"

+ +
    +
  1. 複製以下的文字到名為hellonode.js的檔案中,目前我們只用到Node而已。 + +
    //載入HTTP模組
    +var http = require("http");
    +
    +//創建HTTP 伺服器並監聽8000埠
    +http.createServer(function (request, response) {
    +
    +   // Set the response HTTP header with HTTP status and Content type
    +   response.writeHead(200, {'Content-Type': 'text/plain'});
    +
    +   // Send the response body "Hello World"
    +   response.end('Hello World\n');
    +}).listen(8000);
    +
    +// Print URL for accessing server
    +console.log('Server running at http://127.0.0.1:8000/')
    +
    + +

    這段程式載入『http』模組,並創建一個伺服器 (createServer(),並在8000埠上監聽HTTP requests。 The script then prints a message to the console about what browser URL you can use to test the server. The createServer() function takes as an argument a callback function that will be invoked when an HTTP request is received — this simply returns a response with an HTTP status code of 200 ("OK") and the plain text "Hello World".

    +
  2. +
  3. +
    +

    Note:  Don't worry if you don't understand exactly what this code is doing yet! We'll explain our code in greater detail once we start using Express!

    +
    +
  4. +
  5. Start the server by navigating into the same directory as your hellonode.js file in your command prompt, and calling node along with the script name, like so: +
    >node hellonode.js
    +Server running at http://127.0.0.1:8000/
    +
    +
  6. +
  7. Navigate to the URL (http://127.0.0.1:8000/). If everything is working, the browser should simply display the string "Hello World".
  8. +
+ +

Using NPM

+ +

Next to Node itself, NPM is the most important tool for working with Node applications. NPM is used to fetch any packages (JavaScript libraries) that an application needs for development, testing, and/or production, and may also be used to run tests and tools used in the development process. 

+ +
+

Note: From Node's perspective, Express is just another package that you need to install using NPM and then require in your own code.

+
+ +

You can manually use NPM to separately fetch each needed package. Typically we instead manage dependencies using a plain-text definition file named package.json. This file lists all the dependencies for a specific JavaScript "package", including the package's name, version, description, initial file to execute, production dependencies, development dependencies, versions of Node it can work with, etc. The package.json file should contain everything NPM needs to fetch and run your application (if you were writing a reusable library you could use this definition to upload your package to the npm respository and make it available for other users).

+ +

Adding dependencies

+ +

The following steps show how you can use NPM to download a package, save it into the project dependencies, and then require it in a Node application.

+ +
+

Note: Here we show the instructions to fetch and install the Express package. Later on we'll show how this package, and others, are already specified for us using the Express Application Generator. This section is provided because it is useful to understand how NPM works and what is being created by the application generator.

+
+ +
    +
  1. First create a directory for your new application and navigate into it: +
    mkdir myapp
    +cd myapp
    +
  2. +
  3. Use the npm init command to create a package.json file for your application. This command prompts you for a number of things, including the name and version of your application and the name of the initial entry point file (by default this is index.js). For now, just accept the defaults: +
    npm init
    + +

    If you display the package.json file (cat package.json), you will see the defaults that you accepted, ending with the license.

    + +
    {
    +  "name": "myapp",
    +  "version": "1.0.0",
    +  "description": "",
    +  "main": "index.js",
    +  "scripts": {
    +    "test": "echo \"Error: no test specified\" && exit 1"
    +  },
    +  "author": "",
    +  "license": "ISC"
    +}
    +
    +
  4. +
  5. Now install the Express library in the myapp directory. The package will automatically be saved to the dependencies list in your package.json file. +
    npm install express
    + +

    The dependencies section of your package.json will now appear at the end of the package.json file and will include Express.

    + +
    {
    +  "name": "myapp",
    +  "version": "1.0.0",
    +  "description": "",
    +  "main": "index.js",
    +  "scripts": {
    +    "test": "echo \"Error: no test specified\" && exit 1"
    +  },
    +  "author": "",
    +  "license": "ISC",
    +  "dependencies": {
    +    "express": "^4.16.2"
    +  }
    +}
    +
    +
  6. +
  7. To use the library you call the require() function as shown below. +
    var express = require('express')
    +var app = express()
    +
    +app.get('/', function (req, res) {
    +  res.send('Hello World!')
    +})
    +
    +app.listen(8000, function () {
    +  console.log('Example app listening on port 8000!')
    +})
    +
    + +

    This code shows a minimal "HelloWorld" Express web application. This imports the "express" module and uses it to create a server (app) that listens for HTTP requests on port 8000 and prints a message to the console explaining what browser URL you can use to test the server. The app.get() function only responds to HTTP GET requests with the specified URL path ('/'), in this case by calling a function to send our Hello World! message. 
    +
    + Create a file named index.js in the root of the "myapp" application directory and give it the contents shown above.

    +
  8. +
  9. You can start the server by calling node with the script in your command prompt: +
    >node index.js
    +Example app listening on port 8000
    +
    +
  10. +
  11. Navigate to the URL (http://127.0.0.1:8000/). If everything is working, the browser should simply display the string "Hello World!".
  12. +
+ +

Development dependencies

+ +

If a dependency is only used during development, you should instead save it as a "development dependency" (so that your package users don't have to install it in production). For example, to use the popular JavaScript Linting tool eslint you would call NPM as shown:

+ +
npm install eslint --save-dev
+ +

The following entry would then be added to your application's package.json:

+ +
  "devDependencies": {
+    "eslint": "^4.12.1"
+  }
+
+ +
+

Note: "Linters" are tools that perform static analysis on software in order to recognise and report adherence/non-adherance to some set of coding best practice.

+
+ +

Running tasks

+ +

In addition to defining and fetching dependencies you can also define named scripts in your package.json files and call NPM to execute them with the run-script command. This approach is commonly used to automate running tests and parts of the development or build toolchain (e.g., running tools to minify JavaScript, shrink images, LINT/analyse your code, etc).

+ +
+

Note: Task runners like Gulp and Grunt can also be used to run tests and other external tools.

+
+ +

For example, to define a script to run the eslint development dependency that we specified in the previous section we might add the following script block to our package.json file (assuming that our application source is in a folder /src/js):

+ +
"scripts": {
+  ...
+  "lint": "eslint src/js"
+  ...
+}
+
+ +

To explain a little further, eslint src/js is a command that we could enter in our terminal/command line to run eslint on JavaScript files contained in the src/js directory inside our app directory. Including the above inside our app's package.json file provides a shortcut for this command — lint.

+ +

We would then be able to run eslint using NPM by calling:

+ +
npm run-script lint
+# OR (using the alias)
+npm run lint
+
+ +

This example may not look any shorter than the original command, but you can include much bigger commands inside your npm scripts, including chains of multiple commands. You could identify a single npm script that runs all your tests at once.

+ +

Installing the Express Application Generator

+ +

The Express Application Generator tool generates an Express application "skeleton". Install the generator using NPM as shown (the -g flag installs the tool globally so that you can call it from anywhere):

+ +
npm install express-generator -g
+ +

To create an Express app named "helloworld" with the default settings, navigate to where you want to create it and run the app as shown:

+ +
express helloworld
+ +
+

Note: You can also specify the template library to use and a number of other settings. Use the help command to see all the options:

+ +
express --help
+
+
+ +

NPM will create the new Express app in a sub folder of your current location, displaying build progress on the console. On completion, the tool will display the commands you need to enter to install the Node dependencies and start the app.

+ +
+

The new app will have a package.json file in its root directory. You can open this to see what dependencies are installed, including Express and the template library Jade:

+ +
{
+  "name": "helloworld",
+  "version": "0.0.0",
+  "private": true,
+  "scripts": {
+    "start": "node ./bin/www"
+  },
+  "dependencies": {
+    "body-parser": "~1.18.2",
+    "cookie-parser": "~1.4.3",
+    "debug": "~2.6.9",
+    "express": "~4.15.5",
+    "jade": "~1.11.0",
+    "morgan": "~1.9.0",
+    "serve-favicon": "~2.4.5"
+  }
+}
+
+ +

Install all the dependencies for the helloworld app using NPM as shown:

+ +
cd helloworld
+npm install
+
+ +

Then run the app (the commands are slightly different for Windows and Linux/macOS), as shown below:

+ +
# Run the helloworld on Windows
+SET DEBUG=helloworld:* & npm start
+
+# Run helloworld on Linux/macOS
+DEBUG=helloworld:* npm start
+
+ +

The DEBUG command creates useful logging, resulting in an output like that shown below.

+ +
>SET DEBUG=helloworld:* & npm start
+
+> helloworld@0.0.0 start D:\Github\expresstests\helloworld
+> node ./bin/www
+
+  helloworld:server Listening on port 3000 +0ms
+ +

Open a browser and navigate to http://127.0.0.1:3000/ to see the default Express welcome page.

+ +

Express - Generated App Default Screen

+ +

We'll talk more about the generated app when we get to the article on generating a skeleton application.

+ + + +

總結

+ +

你現在有一個 Node 開發環境在你的電腦上運行,可以用來創造 Express 網頁應用。你也看到如何用 NPM 來加載 Express到一個應用中,以及看到如何使用 Express 應用產生器,創建應用,然後執行它們。

+ +

下一篇文章,我們開始跟著教程一步一步實作,使用這個開發環境與搭配工具,建立一個完整的網頁應用。

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Introduction", "Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs")}}

+ + + +

In this module

+ + diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/author_detail_page/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/author_detail_page/index.html new file mode 100644 index 0000000000..df7a5180e5 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/author_detail_page/index.html @@ -0,0 +1,89 @@ +--- +title: 作者詳情頁面 +slug: Learn/Server-side/Express_Nodejs/Displaying_data/Author_detail_page +translation_of: Learn/Server-side/Express_Nodejs/Displaying_data/Author_detail_page +--- +

作者細節頁面,需要呈現指定作者 Author 的信息,使用 _id 欄位的值(自動產生)識別,接著是這個作者 Author 的所有書本物件 Book 的列表。

+ +

Controller 控制器

+ +

打開 /controllers/authorController.js.

+ +

在檔案最上方,加入底下幾行,引入 asyncBook 模組(作者細節頁面需要它們)。

+ +
var async = require('async');
+var Book = require('../models/book');
+ +

找到 exported author_detail() 控制器方法,並用底下代碼置換。

+ +
// Display detail page for a specific Author.
+exports.author_detail = function(req, res, next) {
+
+    async.parallel({
+        author: function(callback) {
+            Author.findById(req.params.id)
+              .exec(callback)
+        },
+        authors_books: function(callback) {
+          Book.find({ 'author': req.params.id },'title summary')
+          .exec(callback)
+        },
+    }, function(err, results) {
+        if (err) { return next(err); } // Error in API usage.
+        if (results.author==null) { // No results.
+            var err = new Error('Author not found');
+            err.status = 404;
+            return next(err);
+        }
+        // Successful, so render.
+        res.render('author_detail', { title: 'Author Detail', author: results.author, author_books: results.authors_books } );
+    });
+
+};
+
+ +

此處的控制器方法使用 async.parallel(),用平行的方式,查詢作者 Author和相應的書本實例,並附加上繪製本頁面的回調,如果 2 個要求都成功完成,就運行回調。這個方式,就跟前面的種類細節頁面所說明的完全相同。

+ +

View 視圖

+ +

創建 /views/author_detail.pug ,並複制貼上底下的文字。

+ +
extends layout
+
+block content
+
+  h1 Author: #{author.name}
+  p #{author.date_of_birth} - #{author.date_of_death}
+
+  div(style='margin-left:20px;margin-top:20px')
+
+    h4 Books
+
+    dl
+      each book in author_books
+        dt
+          a(href=book.url) #{book.title}
+        dd #{book.summary}
+
+      else
+        p This author has no books.
+
+ +

本模板裡的所有事物,都在先前的章節演示過了。

+ +

它看起來像是?

+ +

運行本應用,並打開瀏覽器訪問 http://localhost:3000/。選擇 All Authors 連結,然後選擇一個作者。如果每個東西都設定正確了,你的網站看起來應該會像底下的截圖。

+ +

Author Detail Page - Express Local Library site

+ +
+

注意:  作者的出生與死亡日期的外觀很醜!我們將在本文最後的自我挑戰處理它。

+
+ +

下一步

+ + diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/author_list_page/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/author_list_page/index.html new file mode 100644 index 0000000000..f207126ed1 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/author_list_page/index.html @@ -0,0 +1,85 @@ +--- +title: Author list page and Genre list page challenge +slug: Learn/Server-side/Express_Nodejs/Displaying_data/Author_list_page +translation_of: Learn/Server-side/Express_Nodejs/Displaying_data/Author_list_page +--- +

作者列表頁面,需要呈現數據庫中所有作者的列表,有每位作者的名字,並連結到作者詳細內容頁面。出生與死亡日期應該在名字後面,並且在同一列。

+ +

Controller 控制器

+ +

作者列表控制器函數,需要獲取所有作者實例的列表,然後將這些實例傳遞給模板進行渲染。

+ +

打開 /controllers/authorController.js。在文件頂部附近,找到導出的 author_list() 控制器方法,並將其替換為以下代碼(更改後的代碼以粗體顯示)。

+ +
// Display list of all Authors.
+exports.author_list = function(req, res, next) {
+
+  Author.find()
+    .sort([['family_name', 'ascending']])
+    .exec(function (err, list_authors) {
+      if (err) { return next(err); }
+      //Successful, so render
+      res.render('author_list', { title: 'Author List', author_list: list_authors });
+    });
+
+};
+ +

The method uses the model's find(), sort() and exec() functions to return all Author objects sorted by family_name in alphabetic order. The callback passed to the exec() method is called with any errors (or null) as the first parameter, or a list of all authors on success. If there is an error it calls the next middleware function with the error value, and if not it renders the author_list(.pug) template, passing the page title and the list of authors (author_list).

+ +

View

+ +

Create /views/author_list.pug and replace its content with the text below.

+ +
extends layout
+
+block content
+  h1= title
+
+  ul
+    each author in author_list
+      li
+        a(href=author.url) #{author.name}
+        |  (#{author.date_of_birth} - #{author.date_of_death})
+
+    else
+      li There are no authors.
+ +

The view follows exactly the same pattern as our other templates.

+ +

What does it look like?

+ +

Run the application and open your browser to http://localhost:3000/. Then select the All authors link. If everything is set up correctly, the page should look something like the following screenshot.

+ +

Author List Page - Express Local Library site

+ +
+

Note: The appearance of the author lifespan dates is ugly! You can improve this using the same approach as we used for the BookInstance list (adding the virtual property for the lifespan to the Author model). This time, however, there are missing dates, and references to nonexistent properties are ignored unless strict mode is in effect. moment() returns the current time, and you don't want missing dates to be formatted as if they were today. One way to deal with this is to define the body of the function that returns a formatted date so it returns a blank string unless the date actually exists. For example:

+ +

return this.date_of_birth ? moment(this.date_of_birth).format('YYYY-MM-DD') : '';

+
+ +

Genre list page—challenge!Edit

+ +

In this section you should implement your own genre list page. The page should display a list of all genres in the database, with each genre linked to its associated detail page. A screenshot of the expected result is shown below.

+ +

Genre List - Express Local Library site

+ +

The genre list controller function needs to get a list of all Genre instances, and then pass these to the template for rendering.

+ +
    +
  1. You will need to edit genre_list() in /controllers/genreController.js
  2. +
  3. The implementation is almost exactly the same as the author_list() controller. +
      +
    • Sort the results by name, in ascending order.
    • +
    +
  4. +
  5. The template to be rendered should be named genre_list.pug.
  6. +
  7. The template to be rendered should be passed the variables title ('Genre List') and genre_list (the list of genres returned from your Genre.find() callback.
  8. +
  9. The view should match the screenshot/requirements above (this should have a very similar structure/format to the Author list view, except for the fact that genres do not have dates).
  10. +
+ +

Next steps

+ +

Return to Express Tutorial Part 5: Displaying library data.

+ +

Proceed to the next subarticle of part 5: Genre detail page.

diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/book_detail_page/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/book_detail_page/index.html new file mode 100644 index 0000000000..31f3d65284 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/book_detail_page/index.html @@ -0,0 +1,112 @@ +--- +title: 書本詳情頁面 +slug: Learn/Server-side/Express_Nodejs/Displaying_data/Book_detail_page +translation_of: Learn/Server-side/Express_Nodejs/Displaying_data/Book_detail_page +--- +

書本細節頁面需要呈現一本指定書本(Book)的信息, 使用它的 _id 字段值(自動產生)做為識別,接著是圖書館中書本實例(BookInstance)的信息。無論我們在哪裡呈現一個作者、種類、或書本實例,都應該連結到它的細節頁面。

+ +

Controller 控制器

+ +

打開 /controllers/bookController.js. ,找到 exported book_detail() 控制器方法,用底下的代碼置換。

+ +
// Display detail page for a specific book.
+exports.book_detail = function(req, res, next) {
+
+    async.parallel({
+        book: function(callback) {
+
+            Book.findById(req.params.id)
+              .populate('author')
+              .populate('genre')
+              .exec(callback);
+        },
+        book_instance: function(callback) {
+
+          BookInstance.find({ 'book': req.params.id })
+          .exec(callback);
+        },
+    }, function(err, results) {
+        if (err) { return next(err); }
+        if (results.book==null) { // No results.
+            var err = new Error('Book not found');
+            err.status = 404;
+            return next(err);
+        }
+        // Successful, so render.
+        res.render('book_detail', { title: 'Title', book:  results.book, book_instances: results.book_instance } );
+    });
+
+};
+
+
+ +
+

注意:  我們不需要用 require 導入 asyncBookInstance,當我們實作主頁面控制器的時候,我們就已經引入這些模組。

+
+ +

此處的控制器方法使用 async.parallel(),用平行的方式找到 Book 以及它的相應複本 (BookInstances) 。這樣的處理方式,就跟上面的 種類細節頁面 所說明的完全相同。

+ +

View 視圖

+ +

創建 /views/book_detail.pug 並加入底下文字。

+ +
extends layout
+
+block content
+  h1 #{title}: #{book.title}
+
+  p #[strong Author:]
+    a(href=book.author.url) #{book.author.name}
+  p #[strong Summary:] #{book.summary}
+  p #[strong ISBN:] #{book.isbn}
+  p #[strong Genre:]&nbsp;
+    each val, index in book.genre
+      a(href=val.url) #{val.name}
+      if index < book.genre.length - 1
+        |,
+
+  div(style='margin-left:20px;margin-top:20px')
+    h4 Copies
+
+    each val in book_instances
+      hr
+      if val.status=='Available'
+        p.text-success #{val.status}
+      else if val.status=='Maintenance'
+        p.text-danger #{val.status}
+      else
+        p.text-warning #{val.status}
+      p #[strong Imprint:] #{val.imprint}
+      if val.status!='Available'
+        p #[strong Due back:] #{val.due_back}
+      p #[strong Id:]&nbsp;
+        a(href=val.url) #{val._id}
+
+    else
+      p There are no copies of this book in the library.
+
+ +

在這個模板裡,幾乎每個東西都在先前的章節演示過了。

+ +
+

注意:  與該書相關的種類列表,在模板中的實作,如以下代碼。除了最後一本書之外,在與本書相關的每個種類之後,都會添加一個逗號。

+ +
  p #[strong Genre:]
+    each val, index in book.genre
+      a(href=val.url) #{val.name}
+      if index < book.genre.length - 1
+        |, 
+
+ +

它看起來像是?

+ +

運行本應用,並打開瀏覽器訪問 http://localhost:3000/。選擇 All books 連結,然後選擇其中一本書。如果每個東西都設定正確了,你的頁面看起來應該像是底下的截圖。

+ +

Book Detail Page - Express Local Library site

+ +

下一步

+ + diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/book_list_page/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/book_list_page/index.html new file mode 100644 index 0000000000..a35b31767d --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/book_list_page/index.html @@ -0,0 +1,72 @@ +--- +title: 書本清單頁面 +slug: Learn/Server-side/Express_Nodejs/Displaying_data/Book_list_page +translation_of: Learn/Server-side/Express_Nodejs/Displaying_data/Book_list_page +--- +

接下做我們將實作書本列表頁面。這個頁面需要呈現數據庫中所有書本的列表,包含每本書的作者、標題,標題將成為一個超連結,連到書本詳細內容頁面。

+ +

控制器

+ +

書本列表控制器函數,需要獲取數據庫中所有 Book對象的列表,然後將這些對像傳給模板進行呈現。

+ +

打開 /controllers/bookController.js. 找到導出的 book_list()控制器方法,並替換為下面的代碼。

+ +
// Display list of all Books.
+exports.book_list = function(req, res, next) {
+
+  Book.find({}, 'title author')
+    .populate('author')
+    .exec(function (err, list_books) {
+      if (err) { return next(err); }
+      //Successful, so render
+      res.render('book_list', { title: 'Book List', book_list: list_books });
+    });
+
+};
+ +

該方法使用模型的find()函數,返回所有 Book 對象,選擇僅返回標題 title 和作者 author,因為我們不需要其他字段(它也會返回 _id 和虛擬欄位字段)。這裡我們還調用 Book 上的 populate(),指定作者 author欄位字段 — 這將用完整的作者信息,替換儲存的書本作者 id。

+ +

成功時,傳遞給查詢的回調,將呈現 book_list(.pug) 模板,將標題 title book_list(包含作者的書本列表)作為變量傳遞。

+ +

View視圖

+ +

創建 /views/book_list.pug 並複制底下的文字。

+ +
extends layout
+
+block content
+  h1= title
+
+  ul
+    each book in book_list
+      li
+        a(href=book.url) #{book.title}
+        |  (#{book.author.name})
+
+    else
+      li There are no books.
+ +

這個視圖擴展了 layout.pug 基本模板,並覆蓋了名為 'content' 的 block 區塊 。它顯示我們從控制器傳入的標題 title(通過 render()方法),然後使用 each-in-else 語法,遍歷 book_list變量。為每本圖書創建一個列表項,以顯示書名,並作為書的詳細信息頁面的鏈接,後面跟著作者姓名。如果 book_list中沒有書,則執行 else 子句,並顯示文字 “沒有書本” 'There are no books'。

+ +

 

+ +
+

注意:   我們使用 book.url,為每本書提供詳細記錄鏈接(我們已經實現了此路由,但尚未實現此頁面)。這是 Book 模型的一個虛擬屬性,它使用模型實例的 _id 字段,生成唯一的 URL 路徑。

+
+ +

在這裡,我們感興趣的是,每本書被定義為兩行,第二行使用管道(上面高亮顯示)。這種方法是必要的,因為如果作者姓名位於上一行,那麼它將成為超鏈接的一部分。

+ +

它看起來像是?

+ +

運行本應用 (參見 測試路由 有相關的命令) ,並打開你的瀏覽器,訪問 http://localhost:3000/。然後選擇所有書本連結 All books。如果每樣東西都設定正確了,你的網站看起來應該像底下的截圖。

+ +

 

+ +

Book List Page - Express Local Library site

+ +

下一步

+ + diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/bookinstance_detail_page_and_challenge/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/bookinstance_detail_page_and_challenge/index.html new file mode 100644 index 0000000000..e04981411c --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/bookinstance_detail_page_and_challenge/index.html @@ -0,0 +1,91 @@ +--- +title: 書本實例詳情頁面與自我挑戰 +slug: >- + Learn/Server-side/Express_Nodejs/Displaying_data/BookInstance_detail_page_and_challenge +translation_of: >- + Learn/Server-side/Express_Nodejs/Displaying_data/BookInstance_detail_page_and_challenge +--- +

書本實例詳情頁面

+ +

BookInstance 詳情頁面,需要呈現每一個 BookInstance 的信息,用 _id 欄位字段值(自動產生)做識別。它包含了 Book 名稱 (也是一個連結,連到 書本細節頁面),接著是紀錄中的其它的信息。

+ +

Controller 控制器

+ +

打開 /controllers/bookinstanceController.js. 找到 exported bookinstance_detail() 控制器方法,並用底下代碼置換。

+ +
// Display detail page for a specific BookInstance.
+exports.bookinstance_detail = function(req, res, next) {
+
+    BookInstance.findById(req.params.id)
+    .populate('book')
+    .exec(function (err, bookinstance) {
+      if (err) { return next(err); }
+      if (bookinstance==null) { // No results.
+          var err = new Error('Book copy not found');
+          err.status = 404;
+          return next(err);
+        }
+      // Successful, so render.
+      res.render('bookinstance_detail', { title: 'Book:', bookinstance:  bookinstance});
+    })
+
+};
+
+ +

該方法使用從 URL(使用路由)中提取的特定書本實例的ID,調用BookInstance.findById(),並通過請求參數(req.params.id),在控制器中訪問。然後調用populate()來獲取相關 Book 的詳細信息。

+ +

View 視圖

+ +

創建 /views/bookinstance_detail.pug ,並複製下面的內容。

+ +
extends layout
+
+block content
+
+  h1 ID: #{bookinstance._id}
+
+  p #[strong Title:]
+    a(href=bookinstance.book.url) #{bookinstance.book.title}
+  p #[strong Imprint:] #{bookinstance.imprint}
+
+  p #[strong Status:]
+    if bookinstance.status=='Available'
+      span.text-success #{bookinstance.status}
+    else if bookinstance.status=='Maintenance'
+      span.text-danger #{bookinstance.status}
+    else
+      span.text-warning #{bookinstance.status}
+
+  if bookinstance.status!='Available'
+    p #[strong Due back:] #{bookinstance.due_back}
+
+ +

本模組中的所有東西,都在先前的章節演示過了。

+ +

它看起來像是?

+ +

運行本應用,並打開瀏覽器訪問 http://localhost:3000//。選擇 All book-instances 連結,然後選擇其中一本。如果每個東西都設定正確了,你的網站看起來應該像是底下的截圖。

+ +

BookInstance Detail Page - Express Local Library site

+ +

自我挑戰

+ +

目前,我們網站上顯示的大多數日期,都使用默認的 JavaScript 格式(例如 Tue Dec 06 2016 15:49:58 GMT+1100 (AUS東部夏令時間))。本文的挑戰,是改善作者Author生命週期日期顯示的外觀信息(死亡/誔生日期)和BookInstance詳細信息頁面,使用格式:December 6th, 2016。

+ +
+

注意:  您可以使用與我們用於 Book Instance List 的相同方法(將生命週期的虛擬屬性,添加到Author模型,並使用 moment 來設置日期字符串的格式)。

+
+ +

這個挑戰的要求:  

+ +
    +
  1. 用 BookInstance 詳細信息頁面中的 due_back_formatted 替換 due_back
  2. +
  3. 更新作者模塊以添加壽命虛擬屬性。壽命應該有兩個值: date_of_birth - date_of_death,這兩個值的格式與 BookInstance.due_back_formatted的日期格式相同。
  4. +
  5. 在當前使用 date_of_birthdate_of_death的所有視圖中,使用 Author.lifespan
  6. +
+ +

下一步

+ + diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/bookinstance_list_page/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/bookinstance_list_page/index.html new file mode 100644 index 0000000000..1b1656258e --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/bookinstance_list_page/index.html @@ -0,0 +1,71 @@ +--- +title: 書本實例清單頁面 +slug: Learn/Server-side/Express_Nodejs/Displaying_data/BookInstance_list_page +translation_of: Learn/Server-side/Express_Nodejs/Displaying_data/BookInstance_list_page +--- +

接下來,我們將實作圖書館中所有書本實例 (BookInstance) 的列表頁面。這個頁面需要包含與每個 BookInstance (鏈接到其詳細信息頁面) 關聯的書本 Book 標題,以及 BookInstance模型中的其他信息,包含每個副本的狀態,印記和唯一ID。唯一ID的文字,應該鏈接到 BookInstance 詳細信息頁面。

+ +

Controller 控制器

+ +

BookInstance列表控制器函數,需要獲取所有書本實例的列表,填充關聯的書本信息,然後將列表傳遞給模板以進行呈現。

+ +

打開 /controllers/bookinstanceController.js。找到導出的 bookinstance_list()控制器方法,並用以下代碼替換它(更改後的代碼以粗體顯示)。

+ +
// Display list of all BookInstances.
+exports.bookinstance_list = function(req, res, next) {
+
+  BookInstance.find()
+    .populate('book')
+    .exec(function (err, list_bookinstances) {
+      if (err) { return next(err); }
+      // Successful, so render
+      res.render('bookinstance_list', { title: 'Book Instance List', bookinstance_list: list_bookinstances });
+    });
+
+};
+ +

此方法使用模型的find()函數,返回所有 BookInstance對象。然後它將一個調用,以菊花鏈方式連接到 populate(),附加書本 book欄位字段,這將使用完整的 Book文檔,替換每個 BookInstance儲存的書本 ID。

+ +

成功時,傳遞給查詢的回調,會呈現 bookinstance_list (.pug)模板,並將標題title和書籍實例列表 bookinstance_list作為變量傳遞。

+ +

View 視圖

+ +

創建 /views/bookinstance_list.pug ,並複制貼上底下的文字。

+ +
extends layout
+
+block content
+  h1= title
+
+  ul
+    each val in bookinstance_list
+      li
+        a(href=val.url) #{val.book.title} : #{val.imprint} -
+        if val.status=='Available'
+          span.text-success #{val.status}
+        else if val.status=='Maintenance'
+          span.text-danger #{val.status}
+        else
+          span.text-warning #{val.status}
+        if val.status!='Available'
+          span  (Due: #{val.due_back} )
+
+    else
+      li There are no book copies in this library.
+ +

這個視圖與其他視圖非常相似。它擴展了佈局,替換內容區塊,顯示從控制器傳入的標題 title,並遍歷 bookinstance_list 中的所有書籍副本。對於每個副本,我們都會顯示它的狀態(用顏色編碼),如果書本不可用,則顯示其預期返回日期。這裡引入了一個新功能 — 我們可以在標籤之後使用點符號表示法,來指定一個類別。因此,span.text-success 將被編譯為 <span class="text-success"> (也可以用 Pug 編寫為 span(class="text-success")。

+ +

 

+ +

它看起來像是?

+ +

運行本應用,打開瀏覽器訪問 http://localhost:3000/,然後選擇 All book-instances 連結。假如每個東西都設定正確了,你的網站看起來應該像是底下的截圖。

+ +

BookInstance List Page - Express Local Library site

+ +

下一步

+ + diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/date_formatting_using_moment/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/date_formatting_using_moment/index.html new file mode 100644 index 0000000000..ecd3ee7f0d --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/date_formatting_using_moment/index.html @@ -0,0 +1,60 @@ +--- +title: 使用 moment 做日期格式化 +slug: Learn/Server-side/Express_Nodejs/Displaying_data/Date_formatting_using_moment +translation_of: Learn/Server-side/Express_Nodejs/Displaying_data/Date_formatting_using_moment +--- +

我們模型的日期預設呈現很難看: Tue Dec 06 2016 15:49:58 GMT+1100 (AUS Eastern Daylight Time)。在本節中,我們將展示如何更新上一節中的 書本實例 BookInstance 列表頁面,以更友好的格式顯示due_date欄位字段:December 6th, 2016。

+ +

我們將使用的方法,是在我們的BookInstance模型中,創建一個返回格式化日期的虛擬屬性。我們將使用 moment 來做實際的格式化,這是一個輕量級 JavaScript日期庫,用於解析,驗證,操作和格式化日期。

+ +
+

注意:  我們可以直接在 Pug 模板中,使用 moment 格式化字符串,或者可以在許多其它地方格式化字符串。使用虛擬屬性,可以使我們獲得格式化的日期,這與我們當前獲取 due_date 的方式完全相同。

+
+ +

安裝 moment

+ +

在項目的根目錄,輸入下列命令

+ +

 

+ +
npm install moment
+ +

創建虛擬屬性

+ +
    +
  1. 打開 ./models/bookinstance.js.
  2. +
  3. 在此頁面最上方,引入 moment. +
    var moment = require('moment');
    +
  4. +
+ +

在 url 屬性後面,加入虛擬屬性 due_back_formatted

+ +
BookInstanceSchema
+.virtual('due_back_formatted')
+.get(function () {
+  return moment(this.due_back).format('MMMM Do, YYYY');
+});
+ +
+

注意:  格式化方法可以使用幾乎任何模式顯示日期。 moment文檔中,可以找到表示不同日期組件的語法。

+
+ +

更新視圖

+ +

打開 /views/bookinstance_list.pug ,然後用 due_back_formatted 取代 due_back

+ +
      if val.status!='Available'
+        //span  (Due: #{val.due_back} )
+        span  (Due: #{val.due_back_formatted} )       
+ +

這就是本章節的全部了。如果你訪問側邊欄的 All book-instances ,你應該會看到所有的歸還日期都更吸引人了!

+ +

下一步

+ + + +

 

diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/flow_control_using_async/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/flow_control_using_async/index.html new file mode 100644 index 0000000000..5271bd6722 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/flow_control_using_async/index.html @@ -0,0 +1,137 @@ +--- +title: 使用 async 進行非同步流控制 +slug: Learn/Server-side/Express_Nodejs/Displaying_data/flow_control_using_async +translation_of: Learn/Server-side/Express_Nodejs/Displaying_data/flow_control_using_async +--- +

有些本地圖書館網頁的控制器代碼,會依賴多重非同步要求的結果,可能會需要以某種特定次序運行,或者以平行方式運行。為了管理流控制,並在我們所有需要用到的信息,都已經可以取用的時候,再繪製網頁,我們將使用許多人採用的 node async 模組。

+ +
+

注意:  在 JavaScript 中有許多其他方法,可以管理異步行為和流控制,包括相對較新的 JavaScript 語言功能,如 Promises

+
+ +

Async 有很多有用的方法(請查看文檔)。一些最重要的功能是:

+ +

 

+ + + +

為什麼需要這麼做?

+ +

我們在 Express 中使用的大多數方法,都是異步的 - 您指定要執行的操作,傳遞回調。該方法立即返回,並在請求的操作完成時,調用回調。按照 Express 中的慣例,回調函數將錯誤值作為第一個參數傳遞(或成功時為 null),並將函數的結果(如果有的話)作為第二個參數傳遞。

+ +

如果控制器只需要執行一個異步操作,來獲取呈現頁面所需的信息,那麼實現很簡單 - 我們只需在回調中呈現模板。下面的代碼片段,顯示了一個函數,該函數呈現模型 SomeModel 的計數(使用Mongoose count()方法):

+ +
exports.some_model_count = function(req, res, next) {
+
+  SomeModel.count({ a_model_field: 'match_value' }, function (err, count) {
+    // ... do something if there is an err
+
+    // On success, render the result by passing count into the render function (here, as the variable 'data').
+    res.render('the_template', { data: count } );
+  });
+}
+
+ +

但是,如果您需要進行多個異步查詢,並且在完成所有操作之前,無法呈現頁面,該怎麼辦?一個單純的實現可以用 “菊花鏈” 連接請求,在先前請求的回調中,啟動後續請求,並在最終回調中呈現響應。這種方法的問題,是我們的請求必須串行運行,即使並行運行它們可能更有效。這也可能導致複雜的嵌套代碼,通常稱為回調地獄

+ +

一個更好的解決方案,是並行執行所有請求,然後在所有查詢完成後執行單個回調。這是 Async 模塊簡化的流操作!

+ +

Asynchronous operations in parallel

+ +

The method async.parallel() is used to run multiple asynchronous operations in parallel.

+ +

The first argument to async.parallel() is a collection of the asynchronous functions to run (an array, object or other iterable). Each function is passed a callback(err, result) which it must call on completion with an error err (which can be null) and an optional results value.

+ +

The optional second argument to  async.parallel() is a callback that will be run when all the functions in the first argument have completed. The callback is invoked with an error argument and a result collection that contains the results of the individual asynchronous operations. The result collection is of the same type as the first argument (i.e. if you pass an array of asynchronous functions, the final callback will be invoked with an array of results). If any of the parallel functions reports an error the callback is invoked early (with the error value).

+ +

The example below shows how this works when we pass an object as the first argument. As you can see, the results are returned in an object with the same property names as the original functions that were passed in.

+ +
async.parallel({
+  one: function(callback) { ... },
+  two: function(callback) { ... },
+  ...
+  something_else: function(callback) { ... }
+  },
+  // optional callback
+  function(err, results) {
+    // 'results' is now equal to: {one: 1, two: 2, ..., something_else: some_value}
+  }
+);
+ +

If you instead pass an array of functions as the first argument, the results will be an array (the array order results will match the original order that the functions were declared—not the order in which they completed).

+ +

Asynchronous operations in series

+ +

The method async.series() is used to run multiple asynchronous operations in sequence, when subsequent functions do not depend on the output of earlier functions. It is essentially declared and behaves in the same way as async.parallel().

+ +
async.series({
+  one: function(callback) { ... },
+  two: function(callback) { ... },
+  ...
+  something_else: function(callback) { ... }
+  },
+  // optional callback after the last asynchronous function completes.
+  function(err, results) {
+    // 'results' is now equals to: {one: 1, two: 2, ..., something_else: some_value} 
+  }
+);
+ +
+

Note: The ECMAScript (JavaScript) language specification states that the order of enumeration of an object is undefined, so it is possible that the functions will not be called in the same order as you specify them on all platforms. If the order really is important, then you should pass an array instead of an object, as shown below.

+
+ +
async.series([
+  function(callback) {
+    // do some stuff ...
+    callback(null, 'one');
+  },
+  function(callback) {
+    // do some more stuff ... 
+    callback(null, 'two');
+  }
+ ],
+  // optional callback
+  function(err, results) {
+  // results is now equal to ['one', 'two'] 
+  }
+);
+ +

Dependent asynchronous operations in series

+ +

The method async.waterfall() is used to run multiple asynchronous operations in sequence when each operation is dependent on the result of the previous operation.

+ +

The callback invoked by each asynchronous function contains null for the first argument and results in subsequent arguments. Each function in the series takes the results arguments of the previous callback as the first parameters, and then a callback function. When all operations are complete, a final callback is invoked with the result of the last operation. The way this works is more clear when you consider the code fragment below (this example is from the async documentation):

+ +
async.waterfall([
+  function(callback) {
+    callback(null, 'one', 'two');
+  },
+  function(arg1, arg2, callback) {
+    // arg1 now equals 'one' and arg2 now equals 'two' 
+    callback(null, 'three');
+  },
+  function(arg1, callback) {
+    // arg1 now equals 'three'
+    callback(null, 'done');
+  }
+], function (err, result) {
+  // result now equals 'done'
+}
+);
+ +

Installing async

+ +

Install the async module using the NPM package manager so that we can use it in our code. You do this in the usual way, by opening a prompt in the root of the LocalLibrary project and enter the following command:

+ +
npm install async
+ +

Next steps

+ + diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/genre_detail_page/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/genre_detail_page/index.html new file mode 100644 index 0000000000..2c7f1e938b --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/genre_detail_page/index.html @@ -0,0 +1,123 @@ +--- +title: Genre detail page +slug: Learn/Server-side/Express_Nodejs/Displaying_data/Genre_detail_page +translation_of: Learn/Server-side/Express_Nodejs/Displaying_data/Genre_detail_page +--- +

種類細節頁面,需要利用_id 字段值 (自動生成) ,以呈現特定種類實例的信息。此頁面應該呈現種類名稱,各個種類的所有書本列表(每本書都連結到書本的細節頁面)。

+ +

 

+ +

Controller 控制器

+ +

打開 /controllers/genreController.js ,並在檔案最上方引用 asyncBook 模組。

+ +
var Book = require('../models/book');
+var async = require('async');
+
+ +

Find the exported genre_detail() controller method and replace it with the following code.

+ +
// Display detail page for a specific Genre.
+exports.genre_detail = function(req, res, next) {
+
+    async.parallel({
+        genre: function(callback) {
+            Genre.findById(req.params.id)
+              .exec(callback);
+        },
+
+        genre_books: function(callback) {
+          Book.find({ 'genre': req.params.id })
+          .exec(callback);
+        },
+
+    }, function(err, results) {
+        if (err) { return next(err); }
+        if (results.genre==null) { // No results.
+            var err = new Error('Genre not found');
+            err.status = 404;
+            return next(err);
+        }
+        // Successful, so render
+        res.render('genre_detail', { title: 'Genre Detail', genre: results.genre, genre_books: results.genre_books } );
+    });
+
+};
+
+ +

The method uses async.parallel() to query the genre name and its associated books in parallel, with the callback rendering the page when (if) both requests complete successfully.

+ +

The ID of the required genre record is encoded at the end of the URL and extracted automatically based on the route definition (/genre/:id). The ID is accessed within the controller via the request parameters: req.params.id. It is used in Genre.findById() to get the current genre. It is also used to get all Book objects that have the genre ID in their genre field: Book.find({ 'genre': req.params.id }).

+ +
+

Note: If the genre does not exist in the database (i.e. it may have been deleted) then findById()  will return successfully with no results. In this case we want to display a "not found" page, so we create an Error object and pass it to the next middleware function in the chain. 

+ +
if (results.genre==null) { // No results.
+    var err = new Error('Genre not found');
+    err.status = 404;
+    return next(err);
+}
+
+ +

The message will then propagate through to our error handling code (this was set up when we generated the app skeleton - for more information see Handling Errors).

+
+ +

The rendered view is genre_detail and it is passed variables for the title, genre and the list of books in this genre (genre_books).

+ +

View

+ +

Create /views/genre_detail.pug and fill it with the text below:

+ +
extends layout
+
+block content
+
+  h1 Genre: #{genre.name}
+
+  div(style='margin-left:20px;margin-top:20px')
+
+    h4 Books
+
+    dl
+    each book in genre_books
+      dt
+        a(href=book.url) #{book.title}
+      dd #{book.summary}
+
+    else
+      p This genre has no books
+
+ +

The view is very similar to all our other templates. The main difference is that we don't use the title passed in for the first heading (though it is used in the underlying layout.pug template to set the page title).

+ +

What does it look like?

+ +

Run the application and open your browser to http://localhost:3000/. Select the All genres link, then select one of the genres (e.g. "Fantasy"). If everything is set up correctly, your page should look something like the following screenshot.

+ +

Genre Detail Page - Express Local Library site

+ +
+

You might get an error similar to this:

+ +
Cast to ObjectId failed for value " 59347139895ea23f9430ecbb" at path "_id" for model "Genre"
+
+ +

This is a mongoose error coming from the req.params.id. To solve this problem, first you need to require mongoose on the genreController.js page like this:

+ +
 var mongoose = require('mongoose');
+
+ +

Then use mongoose.Types.ObjectId() to convert the id to a that can be used. For example:

+ +
exports.genre_detail = function(req, res, next) {
+    var id = mongoose.Types.ObjectId(req.params.id);
+    ...
+
+
+ +

Next steps

+ + diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/home_page/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/home_page/index.html new file mode 100644 index 0000000000..8adc4b11f9 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/home_page/index.html @@ -0,0 +1,133 @@ +--- +title: 主頁 +slug: Learn/Server-side/Express_Nodejs/Displaying_data/Home_page +translation_of: Learn/Server-side/Express_Nodejs/Displaying_data/Home_page +--- +

我們創建的第一個頁面,是網站的主頁面,可以從網站的根目錄 ('/') ,或者 catalog 的根目錄 (catalog/) 訪問。這將呈現一些網站的靜態文字描述,以及動態計算數據庫中不同記錄類型的“計數”。

+ +

我們已經為主頁創建了一個路由。為了完成頁面,我們需要更新控制器函數,以從數據庫中提取記錄的“計數”,並創建一個可用於呈現頁面的視圖(模板)。

+ +

路由

+ +

前面的教程,我們創建 index 頁面路由。此處要提醒的是,所有的路由函式,都定義在 /routes/catalog.js:

+ +
// GET catalog home page.
+router.get('/', book_controller.index);  //This actually maps to /catalog/ because we import the route with a /catalog prefix
+ +

Where the callback function parameter (book_controller.index) is defined in /controllers/bookController.js:

+ +
exports.index = function(req, res, next) {
+    res.send('NOT IMPLEMENTED: Site Home Page');
+}
+ +

It is this controller function that we extend to get information from our models and then render it using a template (view).

+ +

Controller

+ +

The index controller function needs to fetch information about how many Book, BookInstance, available BookInstance, Author, and Genre records we have in the database, render this data in a template to create an HTML page, and then return it in an HTTP response.

+ +
+

Note: We use the countDocuments() method to get the number of instances of each model. This is called on a model with an optional set of conditions to match against in the first argument and a callback in the second argument (as discussed in Using a Database (with Mongoose), and you can also return a Query and then execute it with a callback later. The callback will be returned when the database returns the count, with an error value (or null) as the first parameter and the count of records (or null if there was an error) as the second parameter.

+ +
SomeModel.countDocuments({ a_model_field: 'match_value' }, function (err, count) {
+ // ... do something if there is an err
+ // ... do something with the count if there was no error
+ });
+
+ +

Open /controllers/bookController.js. Near the top of the file you should see the exported index() function.

+ +
var Book = require('../models/book')
+
+exports.index = function(req, res, next) {
+ res.send('NOT IMPLEMENTED: Site Home Page');
+}
+ +

Replace all the code above with the following code fragment. The first thing this does is import (require()) all the models (highlighted in bold). We need to do this because we'll be using them to get our counts of records. It then imports the async module.

+ +
var Book = require('../models/book');
+var Author = require('../models/author');
+var Genre = require('../models/genre');
+var BookInstance = require('../models/bookinstance');
+
+var async = require('async');
+
+exports.index = function(req, res) {
+
+    async.parallel({
+        book_count: function(callback) {
+            Book.countDocuments({}, callback); // Pass an empty object as match condition to find all documents of this collection
+        },
+        book_instance_count: function(callback) {
+            BookInstance.countDocuments({}, callback);
+        },
+        book_instance_available_count: function(callback) {
+            BookInstance.countDocuments({status:'Available'}, callback);
+        },
+        author_count: function(callback) {
+            Author.countDocuments({}, callback);
+        },
+        genre_count: function(callback) {
+            Genre.countDocuments({}, callback);
+        },
+    }, function(err, results) {
+        res.render('index', { title: 'Local Library Home', error: err, data: results });
+    });
+};
+ +

The async.parallel() method is passed an object with functions for getting the counts for each of our models. These functions are all started at the same time. When all of them have completed the final callback is invoked with the counts in the results parameter (or an error).

+ +

On success the callback function calls res.render(), specifying a view (template) named 'index' and an object containing the data that is to be inserted into it (this includes the results object that contains our model counts). The data is supplied as key-value pairs, and can be accessed in the template using the key.

+ +
+

Note: The callback function from async.parallel() above is a little unusual in that we render the page whether or not there was an error (normally you might use a separate execution path for handling the display of errors).

+
+ +

View

+ +

Open /views/index.pug and replace its content with the text below.

+ +
extends layout
+
+block content
+  h1= title
+  p Welcome to #[em LocalLibrary], a very basic Express website developed as a tutorial example on the Mozilla Developer Network.
+
+  h1 Dynamic content
+
+  if error
+    p Error getting dynamic content.
+  else
+    p The library has the following record counts:
+
+    ul
+      li #[strong Books:] !{data.book_count}
+      li #[strong Copies:] !{data.book_instance_count}
+      li #[strong Copies available:] !{data.book_instance_available_count}
+      li #[strong Authors:] !{data.author_count}
+      li #[strong Genres:] !{data.genre_count}
+ +

The view is straightforward. We extend the layout.pug base template, overriding the block named 'content'. The first h1 heading will be the escaped text for the title variable that was passed into the render() function—note the use of the 'h1=' so that the following text is treated as a JavaScript expression. We then include a paragraph introducing the LocalLibrary.

+ +

Under the Dynamic content heading we check whether the error variable passed in from the render() function has been defined. If so, we note the error. If not, we get and list the number of copies of each model from the data variable.

+ +
+

Note: We didn't escape the count values (i.e. we used the !{} syntax) because the count values are calculated. If the information was supplied by end-users then we'd escape the variable for display.

+
+ +

What does it look like?

+ +

At this point we should have created everything needed to display the index page. Run the application and open your browser to http://localhost:3000/. If everything is set up correctly, your site should look something like the following screenshot.

+ +

Home page - Express Local Library site

+ +
+

Note: You won't be able to use the sidebar links yet because the urls, views, and templates for those pages haven't been defined. If you try you'll get errors like "NOT IMPLEMENTED: Book list" for example, depending on the link you click on.  These string literals (which will be replaced with proper data) were specified in the different controllers that live inside your "controllers" file.

+
+ +

Next steps

+ + diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/index.html new file mode 100644 index 0000000000..2073a02bc8 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/index.html @@ -0,0 +1,87 @@ +--- +title: 'Express 教程 5: 呈現圖書館數據' +slug: Learn/Server-side/Express_Nodejs/Displaying_data +translation_of: Learn/Server-side/Express_Nodejs/Displaying_data +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/routes", "Learn/Server-side/Express_Nodejs/forms", "Learn/Server-side/Express_Nodejs")}}
+ +

我們現在準備好要新增網頁,以顯示本地圖書館網站的書本與其它資料。這些網頁將包括一個主頁 ,顯示我們每個模型的型態有多少筆紀錄,以及我們所有模型的清單與細節頁面。藉此,我們將得到從數據庫取得紀錄、以及使用樣版的實務經驗。

+ + + + + + + + + + + + +
前置條件:完成先前教程主題 (包含 Express 教程 4: 路由與控制器)。
目標:了解如何使用非同步模組與 Pug 樣版語言,以及如何從我們的控制器函式中的 URL 得取資料。
+ +

概覽

+ +

在我們先前的教程中,定義了可以用來跟資料庫互動的 Mongoose models ,並創建了一些初始的圖書館紀錄。我們接著創建本地圖書館網站需要的所有路由,但僅使用"空殼控制器" 函式(這些是骨架控制器函式,當一個網頁被存取時,只回傳一個"未實作" 信息)。

+ +

下一步,是為這些顯示圖書館信息的網頁,提供充分的實作(我們將在後面的文章,檢視網頁表單的實作,像是創建、更新、刪除信息)。這包含了更新控制器函式,以利用我們的模型取得紀錄,並定義模板,為使用者顯示這些信息。

+ +

我們在一開始,提供概略的總覽/重點主題,解釋在控制器函式中,如何管理非同步操作,以及如何使用 Pug 撰寫模板。然後我們將為每一個主要的 "唯讀" 網頁提供實作步驟,並且在使用到任何特別的、或新的特性時,會附上簡短的解釋說明。

+ +

本教程的最後,你對路由、非同步函式、視圖、模型如何實際運作,應該有了更好的理解。

+ +

本教程的章節

+ +

本教程分為下列章節,說明為了顯示圖書館網站頁面,如何新增各種特性 。在進入下一個教程之前,你需要閱讀並逐一實作下列章節。

+ +
    +
  1. 使用 async 控制非同步流
  2. +
  3. 模板入門
  4. +
  5. 本地圖書館基礎模板
  6. +
  7. 主頁
  8. +
  9. 書本清單頁面
  10. +
  11. 書本實例清單頁面
  12. +
  13. 日期格式化 - 使用 moment
  14. +
  15. 作者清單頁面、分類清單頁面、與自我挑戰
  16. +
  17. 分類詳情頁面
  18. +
  19. 書本詳情頁面
  20. +
  21. 作者詳情頁面
  22. +
  23. 書本實例詳情頁面與自我挑戰
  24. +
+ +

總結

+ +

我們現在已經為我們的網站,創建了所有 "唯讀" 的頁面: 一個主頁,可以顯示每一個模組的實例數量,書本的列表與詳細信息頁面,書本的實例、作者、分類。沿著目前的學習路徑,我們學到了許多基本知識,有控制器、在非同步作業時管理流控制、使用 Pug 創建視圖、使用模型查詢數據庫、如何從視圖傳送信息到模板、如何創建並擴展模板。而完成挑戰的人,還會學到如何用 moment 處理日期。

+ +

在下一篇文章,我們將依據目前為止學到的知識,創建HTML 表單以及表單管理代碼,開始修改儲存在網站中的資料。

+ +

參閱

+ + + +

{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/routes", "Learn/Server-side/Express_Nodejs/forms", "Learn/Server-side/Express_Nodejs")}}

+ +

 

+ +

本教學連結

+ + + +

 

diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/locallibrary_base_template/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/locallibrary_base_template/index.html new file mode 100644 index 0000000000..c67e82f07e --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/locallibrary_base_template/index.html @@ -0,0 +1,71 @@ +--- +title: 本地圖書館基礎模板 +slug: Learn/Server-side/Express_Nodejs/Displaying_data/LocalLibrary_base_template +translation_of: Learn/Server-side/Express_Nodejs/Displaying_data/LocalLibrary_base_template +--- +

 

+ +

現在我們了解如何使用 Pug 拓展模板,讓我們開始項目,創建一個基礎模板。這個模板會有一個側邊欄,連結到本教程中將要創建的各個頁面(例如,呈現並創建書本、種類、作者等等),以及一個主要內容區域,我們將在每個頁面中進行覆寫。

+ +

開啟 /views/layout.pug ,並以下列代碼,置換其內容。

+ +
doctype html
+html(lang='en')
+  head
+    title= title
+    meta(charset='utf-8')
+    meta(name='viewport', content='width=device-width, initial-scale=1')
+    link(rel='stylesheet', href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css')
+    script(src='https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js')
+    script(src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js')
+    link(rel='stylesheet', href='/stylesheets/style.css')
+  body
+    div(class='container-fluid')
+      div(class='row')
+        div(class='col-sm-2')
+          block sidebar
+            ul(class='sidebar-nav')
+              li
+                a(href='/catalog') Home
+              li
+                a(href='/catalog/books') All books
+              li
+                a(href='/catalog/authors') All authors
+              li
+                a(href='/catalog/genres') All genres
+              li
+                a(href='/catalog/bookinstances') All book-instances
+              li
+                hr
+              li
+                a(href='/catalog/author/create') Create new author
+              li
+                a(href='/catalog/genre/create') Create new genre
+              li
+                a(href='/catalog/book/create') Create new book
+              li
+                a(href='/catalog/bookinstance/create') Create new book instance (copy)
+
+        div(class='col-sm-10')
+          block content
+ +

此模板使用(並包含)來自 Bootstrap 的 JavaScript 和 CSS ,以改進 HTML 頁面的佈局和呈現方式。使用 Bootstrap 或其它客戶端網頁框架,是一種快速的方式,可以創建吸引人的網頁,能夠良好地適應不同的瀏覽器尺寸,並且允許我們處理頁面的呈現,而不需要糾纒於任何不同尺寸的細節—此處我們只想專注於伺服端代碼!

+ +

佈局的安排應該相當明白,假如你已經閱讀了之前的 模板入門。注意,使用 block content 當做定位符號,放到頁面內容將要放置的地方。

+ +

基礎模板也參考了一個本地 css 檔 (style.css) ,此檔提供了一些額外的樣式。打開 /public/stylesheets/style.css ,並用底下的 CSS 代碼,取代它的內容:

+ +
.sidebar-nav {
+    margin-top: 20px;
+    padding: 0;
+    list-style: none;
+}
+ +

當我們開始運行網站時,我們應該看到側邊欄出現!在本教程的下個部分,我們將使用以上的佈局,來定義各個頁面。

+ +

下一步

+ + diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/template_primer/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/template_primer/index.html new file mode 100644 index 0000000000..af976b7155 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/template_primer/index.html @@ -0,0 +1,149 @@ +--- +title: 模板入門 +slug: Learn/Server-side/Express_Nodejs/Displaying_data/Template_primer +translation_of: Learn/Server-side/Express_Nodejs/Displaying_data/Template_primer +--- +

模板是一個文字檔,定義了一個輸出檔的結構或者排版,使用定位符號表示,當模板被繪製時,資料將插入到何處(在Express,模板被稱為視圖)。

+ +

Express 模板選擇

+ +

Express 可以與許多不同的模板渲染引擎一起使用。在本教程中,我們使用 Pug(以前稱為 Jade)作為模板。這是最流行的 Node 模板語言,並且官方將自身描述為 “用於編寫 HTML,語法乾淨且空格敏感,受 Haml 影響很大”。

+ +

不同的模板語言使用不同的方法,來定義佈局和標記數據的佔位符 — 一些使用 HTML 來定義佈局,而另一些則使用可以編譯為 HTML 的不同標記格式。 Pug 是第二種類型;它使用 HTML 的表示形式,其中任何行中的第一個單詞,通常表示HTML元素,後續行中的縮進,用於表示嵌套在這些元素中的任何內容。結果是一個頁面定義直接轉換為 HTML,但可以說更簡潔,更容易閱讀。

+ +
+

Note: The downside of using Pug is that it is sensitive to indentation and whitespace (if you add an extra space in the wrong place you may get an unhelpful error code). However once you have your templates in place, they are very easy to read and maintain.

+
+ +

Template configuration

+ +

The LocalLibrary was configured to use Pug when we created the skeleton website. You should see the pug module included as a dependency in the website's package.json file, and the following configuration settings in the app.js file. The settings tell us that we're using pug as the view engine, and that Express should search for templates in the /views subdirectory.

+ +
// View engine setup.
+app.set('views', path.join(__dirname, 'views'));
+app.set('view engine', 'pug');
+ +

If you look in the views directory you will see the .pug files for the project's default views. These include the view for the home page (index.pug) and base template (layout.pug) that we will need to replace with our own content.

+ +
/express-locallibrary-tutorial  //the project root
+  /views
+    error.pug
+    index.pug
+    layout.pug
+
+ +

Template syntax

+ +

The example template file below shows off many of Pug's most useful features.

+ +

The first thing to notice is that the file maps the structure of a typical HTML file, with the first word in (almost) every line being an HTML element, and indentation being used to indicate nested elements. So for example, the body element is inside an html element, and paragraph elements (p) are within the body element, etc. Non-nested elements (e.g. individual paragraphs) are on separate lines.

+ +
doctype html
+html(lang="en")
+  head
+    title= title
+    script(type='text/javascript').
+  body
+    h1= title
+
+    p This is a line with #[em some emphasis] and #[strong strong text] markup.
+    p This line has un-escaped data: !{'<em> is emphasised</em>'} and escaped data: #{'<em> is not emphasised</em>'}.
+      | This line follows on.
+    p= 'Evaluated and <em>escaped expression</em>:' + title
+
+    <!-- You can add HTML comments directly -->
+    // You can add single line JavaScript comments and they are generated to HTML comments
+    //- Introducing a single line JavaScript comment with "//-" ensures the comment isn't rendered to HTML
+
+    p A line with a link
+      a(href='/catalog/authors') Some link text
+      |  and some extra text.
+
+    #container.col
+      if title
+        p A variable named "title" exists.
+      else
+        p A variable named "title" does not exist.
+      p.
+        Pug is a terse and simple template language with a
+        strong focus on performance and powerful features.
+
+    h2 Generate a list
+
+    ul
+      each val in [1, 2, 3, 4, 5]
+        li= val
+ +

Element attributes are defined in parentheses after their associated element. Inside the parentheses, the attributes are defined in comma- or whitespace- separated lists of the pairs of attribute names and attribute values, for example:

+ + + +

The values of all attributes are escaped (e.g. characters like ">" are converted to their HTML code equivalents like "&gt;") to prevent injection of JavaScript/cross-site scripting attacks.

+ +

If a tag is followed by the equals sign, the following text is treated as a JavaScript expression. So for example, in the first line below, the content of the h1 tag will be variable title (either defined in the file or passed into the template from Express). In the second line the paragraph content is a text string concatented with the title variable. In both cases the default behaviour is to escape the line.

+ +
h1= title
+p= 'Evaluated and <em>escaped expression</em>:' + title
+ +

If there is no equals symbol after the tag then the content is treated as plain text. Within the plain text you can insert escaped and unescaped data using the #{} and !{} syntax, as shown below. You can also add raw HTML within the plain text.

+ +
p This is a line with #[em some emphasis] and #[strong strong text] markup.
+p This line has an un-escaped string: !{'<em> is emphasised</em>'}, an escaped string: #{'<em> is not emphasised</em>'}, and escaped variables: #{title}.
+ +
+

Tip: You will almost always want to escape data from users (via the #{} syntax). Data that can be trusted (e.g. generated counts of records, etc.) may be displayed without escaping the values.

+
+ +

You can use the pipe ('|') character at the beginning of a line to indicate "plain text". For example, the additional text shown below will be displayed on the same line as the preceding anchor, but will not be linked.

+ +
a(href='http://someurl/') Link text
+| Plain text
+ +

Pug allows you to perform conditional operations using if, else , else if and unless—for example:

+ +
if title
+  p A variable named "title" exists
+else
+  p A variable named "title" does not exist
+ +

You can also perform loop/iteration operations using each-in or while syntax. In the code fragment below we've looped through an array to display a list of variables (note the use of the 'li=' to evaluate the "val" as a variable below. The value you iterate across can also be passed into the template as a variable!

+ +
ul
+  each val in [1, 2, 3, 4, 5]
+    li= val
+ +

The syntax also supports comments (that can be rendered in the output—or not—as you choose), mixins to create reusable blocks of code, case statements, and many other features. For more detailed information see The Pug docs.

+ +

Extending templates

+ +

Across a site, it is usual for all pages to have a common structure, including standard HTML markup for the head, footer, navigation, etc. Rather than forcing developers to duplicate this "boilerplate" in every page, Pug allows you to declare a base template and then extend it, replacing just the bits that are different for each specific page.

+ +

For example, the base template layout.pug created in our skeleton project looks like this:

+ +
doctype html
+html
+  head
+    title= title
+    link(rel='stylesheet', href='/stylesheets/style.css')
+  body
+    block content
+ +

The block tag is used to mark up sections of content that may be replaced in a derived template (if the block is not redefined then its implementation in the base class is used).

+ +

The default index.pug (created for our skeleton project) shows how we override the base template. The extends tag identifies the base template to use, and then we use block section_name to indicate the new content of the section that we will override.

+ +
extends layout
+
+block content
+  h1= title
+  p Welcome to #{title}
+ +

Next steps

+ + diff --git a/files/zh-tw/learn/server-side/express_nodejs/forms/create_author_form/index.html b/files/zh-tw/learn/server-side/express_nodejs/forms/create_author_form/index.html new file mode 100644 index 0000000000..9d4563376e --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/forms/create_author_form/index.html @@ -0,0 +1,155 @@ +--- +title: Create Author form +slug: Learn/Server-side/Express_Nodejs/forms/Create_author_form +translation_of: Learn/Server-side/Express_Nodejs/forms/Create_author_form +--- +

Edi本章節演示,如何為創建作者對象 Author定義一個頁面。

+ +

導入驗證和清理方法

+ +

為了在種類表單使用 express 驗證器,我們必須用 require 導入我們想用的函式。

+ +

打開 /controllers/authorController.js,並在檔案最上方,加入底下幾行:

+ +
const { body,validationResult } = require('express-validator/check');
+const { sanitizeBody } = require('express-validator/filter');
+ +

Controller—get route

+ +

Find the exported author_create_get() controller method and replace it with the following code. This simply renders the author_form.pug view, passing a title variable.

+ +
// Display Author create form on GET.
+exports.author_create_get = function(req, res, next) {
+    res.render('author_form', { title: 'Create Author'});
+};
+ +

Controller—post route

+ +

Find the exported author_create_post() controller method, and replace it with the following code.

+ +
// Handle Author create on POST.
+exports.author_create_post = [
+
+    // Validate fields.
+    body('first_name').isLength({ min: 1 }).trim().withMessage('First name must be specified.')
+        .isAlphanumeric().withMessage('First name has non-alphanumeric characters.'),
+    body('family_name').isLength({ min: 1 }).trim().withMessage('Family name must be specified.')
+        .isAlphanumeric().withMessage('Family name has non-alphanumeric characters.'),
+    body('date_of_birth', 'Invalid date of birth').optional({ checkFalsy: true }).isISO8601(),
+    body('date_of_death', 'Invalid date of death').optional({ checkFalsy: true }).isISO8601(),
+
+    // Sanitize fields.
+    sanitizeBody('first_name').trim().escape(),
+    sanitizeBody('family_name').trim().escape(),
+    sanitizeBody('date_of_birth').toDate(),
+    sanitizeBody('date_of_death').toDate(),
+
+    // Process request after validation and sanitization.
+    (req, res, next) => {
+
+        // Extract the validation errors from a request.
+        const errors = validationResult(req);
+
+        if (!errors.isEmpty()) {
+            // There are errors. Render form again with sanitized values/errors messages.
+            res.render('author_form', { title: 'Create Author', author: req.body, errors: errors.array() });
+            return;
+        }
+        else {
+            // Data from form is valid.
+
+            // Create an Author object with escaped and trimmed data.
+            var author = new Author(
+                {
+                    first_name: req.body.first_name,
+                    family_name: req.body.family_name,
+                    date_of_birth: req.body.date_of_birth,
+                    date_of_death: req.body.date_of_death
+                });
+            author.save(function (err) {
+                if (err) { return next(err); }
+                // Successful - redirect to new author record.
+                res.redirect(author.url);
+            });
+        }
+    }
+];
+ +

The structure and behaviour of this code is almost exactly the same as for creating a Genre object. First we validate and sanitize the data. If the data is invalid then we re-display the form along with the data that was originally entered by the user and a list of error messages. If the data is valid then we save the new author record and redirect the user to the author detail page.

+ +
+

Note:  Unlike with the Genre post handler, we don't check whether the Author object already exists before saving it. Arguably we should, though as it is now we can have multiple authors with the same name.

+
+ +

The validation code demonstrates several new features:

+ + + + + +

View

+ +

Create /views/author_form.pug and copy in the text below.

+ +
extends layout
+
+block content
+  h1=title
+
+  form(method='POST' action='')
+    div.form-group
+      label(for='first_name') First Name:
+      input#first_name.form-control(type='text' placeholder='First name (Christian) last' name='first_name' required='true' value=(undefined===author ? '' : author.first_name) )
+      label(for='family_name') Family Name:
+      input#family_name.form-control(type='text' placeholder='Family name (surname)' name='family_name' required='true' value=(undefined===author ? '' : author.family_name))
+    div.form-group
+      label(for='date_of_birth') Date of birth:
+      input#date_of_birth.form-control(type='date' name='date_of_birth' value=(undefined===author ? '' : author.date_of_birth) )
+    button.btn.btn-primary(type='submit') Submit
+  if errors
+    ul
+      for error in errors
+        li!= error.msg
+ +

The structure and behaviour for this view is exactly the same as for the genre_form.pug template, so we won't describe it again.

+ +
+

Note: Some browsers don’t support the input type=“date”, so you won’t get the datepicker widget or the default dd/mm/yyyy placeholder, but will instead get an empty plain text field. One workaround is to explicitly add the attribute placeholder='dd/mm/yyyy' so that on less capable browsers you will still get information about the desired text format.

+
+ +

Challenge: Adding the date of death

+ +

The template above is missing a field for entering the date_of_death. Create the field following the same pattern as the date of birth form group!

+ +

What does it look like?

+ +

Run the application, open your browser to http://localhost:3000/, then select the Create new author link. If everything is set up correctly, your site should look something like the following screenshot. After you enter a value, it should be saved and you'll be taken to the author detail page.

+ +

Author Create Page - Express Local Library site

+ +
+

Note: If you experiment with various input formats for the dates, you may find that the format yyyy-mm-dd misbehaves. This is because JavaScript treats date strings as including the time of 0 hours, but additionally treats date strings in that format (the ISO 8601 standard) as including the time 0 hours UTC, rather than the local time. If your time zone is west of UTC, the date display, being local, will be one day before the date you entered. This is one of several complexities (such as multi-word family names and multi-author books) that we are not addressing here.

+
+ +

Next steps

+ + diff --git a/files/zh-tw/learn/server-side/express_nodejs/forms/create_book_form/index.html b/files/zh-tw/learn/server-side/express_nodejs/forms/create_book_form/index.html new file mode 100644 index 0000000000..c15b2ca385 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/forms/create_book_form/index.html @@ -0,0 +1,214 @@ +--- +title: Create Book form +slug: Learn/Server-side/Express_Nodejs/forms/Create_book_form +translation_of: Learn/Server-side/Express_Nodejs/forms/Create_book_form +--- +

Edit此章節展示如何定義頁面/表單以創建Book對象。這比相同的作者Author或種類Genre頁面稍微複雜一點,因為我們需要在我們的書本表單中,獲取並顯示可用的作者和種類記錄。

+ +

 

+ +

導入驗證和清理方法

+ +

打開 /controllers/bookController.js,並在文件頂部添加以下幾行:

+ +
const { body,validationResult } = require('express-validator/check');
+const { sanitizeBody } = require('express-validator/filter');
+ +

Controller—get route

+ +

Find the exported book_create_get() controller method and replace it with the following code.

+ +
// Display book create form on GET.
+exports.book_create_get = function(req, res, next) {
+
+    // Get all authors and genres, which we can use for adding to our book.
+    async.parallel({
+        authors: function(callback) {
+            Author.find(callback);
+        },
+        genres: function(callback) {
+            Genre.find(callback);
+        },
+    }, function(err, results) {
+        if (err) { return next(err); }
+        res.render('book_form', { title: 'Create Book', authors: results.authors, genres: results.genres });
+    });
+
+};
+ +

This uses the async module (described in Express Tutorial Part 5: Displaying library data) to get all Author and Genre objects. These are then passed to the view book_form.pug as variables named authors and genres (along with the page title).

+ +

Controller—post route

+ +

Find the exported book_create_post() controller method and replace it with the following code.

+ +
// Handle book create on POST.
+exports.book_create_post = [
+    // Convert the genre to an array.
+    (req, res, next) => {
+        if(!(req.body.genre instanceof Array)){
+            if(typeof req.body.genre==='undefined')
+            req.body.genre=[];
+            else
+            req.body.genre=new Array(req.body.genre);
+        }
+        next();
+    },
+
+    // Validate fields.
+    body('title', 'Title must not be empty.').isLength({ min: 1 }).trim(),
+    body('author', 'Author must not be empty.').isLength({ min: 1 }).trim(),
+    body('summary', 'Summary must not be empty.').isLength({ min: 1 }).trim(),
+    body('isbn', 'ISBN must not be empty').isLength({ min: 1 }).trim(),
+
+    // Sanitize fields (using wildcard).
+    sanitizeBody('*').trim().escape(),
+
+    // Process request after validation and sanitization.
+    (req, res, next) => {
+
+        // Extract the validation errors from a request.
+        const errors = validationResult(req);
+
+        // Create a Book object with escaped and trimmed data.
+        var book = new Book(
+          { title: req.body.title,
+            author: req.body.author,
+            summary: req.body.summary,
+            isbn: req.body.isbn,
+            genre: req.body.genre
+           });
+
+        if (!errors.isEmpty()) {
+            // There are errors. Render form again with sanitized values/error messages.
+
+            // Get all authors and genres for form.
+            async.parallel({
+                authors: function(callback) {
+                    Author.find(callback);
+                },
+                genres: function(callback) {
+                    Genre.find(callback);
+                },
+            }, function(err, results) {
+                if (err) { return next(err); }
+
+                // Mark our selected genres as checked.
+                for (let i = 0; i < results.genres.length; i++) {
+                    if (book.genre.indexOf(results.genres[i]._id) > -1) {
+                        results.genres[i].checked='true';
+                    }
+                }
+                res.render('book_form', { title: 'Create Book',authors:results.authors, genres:results.genres, book: book, errors: errors.array() });
+            });
+            return;
+        }
+        else {
+            // Data from form is valid. Save book.
+            book.save(function (err) {
+                if (err) { return next(err); }
+                   //successful - redirect to new book record.
+                   res.redirect(book.url);
+                });
+        }
+    }
+];
+ +

The structure and behaviour of this code is almost exactly the same as for creating a Genre or Author object. First we validate and sanitize the data. If the data is invalid then we re-display the form along with the data that was originally entered by the user and a list of error messages. If the data is valid, we then save the new Book record and redirect the user to the book detail page.

+ +

The first main difference with respect to the other form handling code is that we use a wildcard to trim and escape all fields in one go (rather than sanitising them individually):

+ +
sanitizeBody('*').trim().escape(),
+ +

The next main difference with respect to the other form handling code is how we sanitize the genre information. The form returns an array of Genre items (while for other fields it returns a string). In order to validate the information we first convert the request to an array (required for the next step).

+ +
// Convert the genre to an array.
+(req, res, next) => {
+    if(!(req.body.genre instanceof Array)){
+        if(typeof req.body.genre==='undefined')
+        req.body.genre=[];
+        else
+        req.body.genre=new Array(req.body.genre);
+    }
+    next();
+},
+ +

We then use a wildcard (*) in the sanitiser to individually validate each of the genre array entries. The code below shows how - this translates to "sanitise every item below key genre".

+ +
sanitizeBody('genre.*').trim().escape(),
+ +

The final difference with respect to the other form handling code is that we need to pass in all existing genres and authors to the form. In order to mark the genres that were checked by the user we iterate through all the genres and add the checked='true' parameter to those that were in our post data (as reproduced in the code fragment below).

+ +
// Mark our selected genres as checked.
+for (let i = 0; i < results.genres.length; i++) {
+    if (book.genre.indexOf(results.genres[i]._id) > -1) {
+        // Current genre is selected. Set "checked" flag.
+        results.genres[i].checked='true';
+    }
+}
+ +

View

+ +

Create /views/book_form.pug and copy in the text below.

+ +
extends layout
+
+block content
+  h1= title
+
+  form(method='POST' action='')
+    div.form-group
+      label(for='title') Title:
+      input#title.form-control(type='text', placeholder='Name of book' name='title' required='true' value=(undefined===book ? '' : book.title) )
+    div.form-group
+      label(for='author') Author:
+      select#author.form-control(type='select', placeholder='Select author' name='author' required='true' )
+        for author in authors
+          if book
+            option(value=author._id selected=(author._id.toString()==book.author ? 'selected' : false) ) #{author.name}
+          else
+            option(value=author._id) #{author.name}
+    div.form-group
+      label(for='summary') Summary:
+      input#summary.form-control(type='textarea', placeholder='Summary' name='summary' value=(undefined===book ? '' : book.summary) required='true')
+    div.form-group
+      label(for='isbn') ISBN:
+      input#isbn.form-control(type='text', placeholder='ISBN13' name='isbn' value=(undefined===book ? '' : book.isbn) required='true')
+    div.form-group
+      label Genre:
+      div
+        for genre in genres
+          div(style='display: inline; padding-right:10px;')
+            input.checkbox-input(type='checkbox', name='genre', id=genre._id, value=genre._id, checked=genre.checked )
+            label(for=genre._id) #{genre.name}
+    button.btn.btn-primary(type='submit') Submit
+
+  if errors
+    ul
+      for error in errors
+        li!= error.msg
+ +

The view structure and behaviour is almost the same as for the genre_form.pug template.

+ +

The main differences are in how we implement the selection-type fields: Author and Genre.

+ + + +

What does it look like?

+ +

Run the application, open your browser to http://localhost:3000/, then select the Create new book link. If everything is set up correctly, your site should look something like the following screenshot. After you submit a valid book, it should be saved and you'll be taken to the book detail page.

+ +

+ +

Next steps

+ +

Return to Express Tutorial Part 6: Working with forms.

+ +

Proceed to the next subarticle of part 6: Create BookInstance form.

diff --git a/files/zh-tw/learn/server-side/express_nodejs/forms/create_bookinstance_form/index.html b/files/zh-tw/learn/server-side/express_nodejs/forms/create_bookinstance_form/index.html new file mode 100644 index 0000000000..14288f4678 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/forms/create_bookinstance_form/index.html @@ -0,0 +1,150 @@ +--- +title: Create BookInstance form +slug: Learn/Server-side/Express_Nodejs/forms/Create_BookInstance_form +translation_of: Learn/Server-side/Express_Nodejs/forms/Create_BookInstance_form +--- +

Edi本章節演示如何定義一個頁面/表單,以創建 BookInstance 物件。這很像我們用來創建書本 Book 物件的表單。

+ +

導入驗證和清理方法

+ +

打開 /controllers/bookinstanceController.js,並在檔案最上方,加入以下幾行:

+ +
const { body,validationResult } = require('express-validator/check');
+const { sanitizeBody } = require('express-validator/filter');
+ +

Controller—get route

+ +

At the top of the file, require the Book module (needed because each BookInstance is associated with a particular Book).

+ +
var Book = require('../models/book');
+ +

Find the exported bookinstance_create_get() controller method and replace it with the following code.

+ +
// Display BookInstance create form on GET.
+exports.bookinstance_create_get = function(req, res, next) {
+
+    Book.find({},'title')
+    .exec(function (err, books) {
+      if (err) { return next(err); }
+      // Successful, so render.
+      res.render('bookinstance_form', {title: 'Create BookInstance', book_list:books});
+    });
+
+};
+ +

The controller gets a list of all books (book_list) and passes it to the view bookinstance_form.pug (along with the title)

+ +

Controller—post route

+ +

Find the exported bookinstance_create_post() controller method and replace it with the following code.

+ +
// Handle BookInstance create on POST.
+exports.bookinstance_create_post = [
+
+    // Validate fields.
+    body('book', 'Book must be specified').isLength({ min: 1 }).trim(),
+    body('imprint', 'Imprint must be specified').isLength({ min: 1 }).trim(),
+    body('due_back', 'Invalid date').optional({ checkFalsy: true }).isISO8601(),
+
+    // Sanitize fields.
+    sanitizeBody('book').trim().escape(),
+    sanitizeBody('imprint').trim().escape(),
+    sanitizeBody('status').trim().escape(),
+    sanitizeBody('due_back').toDate(),
+
+    // Process request after validation and sanitization.
+    (req, res, next) => {
+
+        // Extract the validation errors from a request.
+        const errors = validationResult(req);
+
+        // Create a BookInstance object with escaped and trimmed data.
+        var bookinstance = new BookInstance(
+          { book: req.body.book,
+            imprint: req.body.imprint,
+            status: req.body.status,
+            due_back: req.body.due_back
+           });
+
+        if (!errors.isEmpty()) {
+            // There are errors. Render form again with sanitized values and error messages.
+            Book.find({},'title')
+                .exec(function (err, books) {
+                    if (err) { return next(err); }
+                    // Successful, so render.
+                    res.render('bookinstance_form', { title: 'Create BookInstance', book_list : books, selected_book : bookinstance.book._id , errors: errors.array(), bookinstance:bookinstance });
+            });
+            return;
+        }
+        else {
+            // Data from form is valid.
+            bookinstance.save(function (err) {
+                if (err) { return next(err); }
+                   // Successful - redirect to new record.
+                   res.redirect(bookinstance.url);
+                });
+        }
+    }
+];
+ +

The structure and behaviour of this code is the same as for creating our other objects. First we validate and sanitize the data. If the data is invalid, we then re-display the form along with the data that was originally entered by the user and a list of error messages. If the data is valid, we save the new BookInstance record and redirect the user to the detail page.

+ +

View

+ +

Create /views/bookinstance_form.pug and copy in the text below.

+ +
extends layout
+
+block content
+  h1=title
+
+  form(method='POST' action='')
+    div.form-group
+      label(for='book') Book:
+      select#book.form-control(type='select' placeholder='Select book' name='book' required='true')
+        for book in book_list
+          if bookinstance
+            option(value=book._id selected=(bookinstance.book.toString()==book._id.toString() ? 'selected' : false)) #{book.title}
+          else
+            option(value=book._id) #{book.title}
+
+    div.form-group
+      label(for='imprint') Imprint:
+      input#imprint.form-control(type='text' placeholder='Publisher and date information' name='imprint' required='true' value=(undefined===bookinstance ? '' : bookinstance.imprint))
+    div.form-group
+      label(for='due_back') Date when book available:
+      input#due_back.form-control(type='date' name='due_back' value=(undefined===bookinstance ? '' : bookinstance.due_back))
+
+    div.form-group
+      label(for='status') Status:
+      select#status.form-control(type='select' placeholder='Select status' name='status' required='true')
+        option(value='Maintenance') Maintenance
+        option(value='Available') Available
+        option(value='Loaned') Loaned
+        option(value='Reserved') Reserved
+
+    button.btn.btn-primary(type='submit') Submit
+
+  if errors
+    ul
+      for error in errors
+        li!= error.msg
+ +

The view structure and behaviour is almost the same as for the book_form.pug template, so we won't go over it again.

+ +
+

Note: The above template hard-codes the Status values (Maintenance, Available, etc.) and does not "remember" the user's entered values. Should you so wish, consider reimplementing the list, passing in option data from the controller and setting the selected value when the form is re-displayed.

+
+ +

What does it look like?

+ +

Run the application and open your browser to http://localhost:3000/. Then select the Create new book instance (copy) link. If everything is set up correctly, your site should look something like the following screenshot. After you submit a valid BookInstance, it should be saved and you'll be taken to the detail page.

+ +

+ +

Next steps

+ + diff --git a/files/zh-tw/learn/server-side/express_nodejs/forms/create_genre_form/index.html b/files/zh-tw/learn/server-side/express_nodejs/forms/create_genre_form/index.html new file mode 100644 index 0000000000..3e648e48ea --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/forms/create_genre_form/index.html @@ -0,0 +1,294 @@ +--- +title: 創建種類表單 +slug: Learn/Server-side/Express_Nodejs/forms/Create_genre_form +translation_of: Learn/Server-side/Express_Nodejs/forms/Create_genre_form +--- +

本章節演示如何定義我們的頁面,創建Genre 物件(這是一個很好的起點,因為類型Genre只有一個欄位,就是它的名稱 name,沒有依賴項)。像任何其他頁面一樣,我們需要設置路由,控制器和視圖。

+ +

 

+ +

引入驗證與無害化方法

+ +

在我們的控制器中使用 express-validator 驗證器,我們必須導入我們想要從 'express-validator/check' 和 'express-validator/filter' 模塊中使用的函數。

+ +

打開 /controllers/genreController.js,並在文件頂部添加以下幾行:

+ +
const { body,validationResult } = require('express-validator/check');
+const { sanitizeBody } = require('express-validator/filter');
+ +

Controller—get route

+ +

Find the exported genre_create_get() controller method and replace it with the following code. This simply renders the genre_form.pug view, passing a title variable.

+ +
// Display Genre create form on GET.
+exports.genre_create_get = function(req, res, next) {
+    res.render('genre_form', { title: 'Create Genre' });
+};
+ +

Controller—post route

+ +

Find the exported genre_create_post() controller method and replace it with the following code.

+ +
// Handle Genre create on POST.
+exports.genre_create_post =  [
+
+    // Validate that the name field is not empty.
+    body('name', 'Genre name required').isLength({ min: 1 }).trim(),
+
+    // Sanitize (trim and escape) the name field.
+    sanitizeBody('name').trim().escape(),
+
+    // Process request after validation and sanitization.
+    (req, res, next) => {
+
+        // Extract the validation errors from a request.
+        const errors = validationResult(req);
+
+        // Create a genre object with escaped and trimmed data.
+        var genre = new Genre(
+          { name: req.body.name }
+        );
+
+
+        if (!errors.isEmpty()) {
+            // There are errors. Render the form again with sanitized values/error messages.
+            res.render('genre_form', { title: 'Create Genre', genre: genre, errors: errors.array()});
+        return;
+        }
+        else {
+            // Data from form is valid.
+            // Check if Genre with same name already exists.
+            Genre.findOne({ 'name': req.body.name })
+                .exec( function(err, found_genre) {
+                     if (err) { return next(err); }
+
+                     if (found_genre) {
+                         // Genre exists, redirect to its detail page.
+                         res.redirect(found_genre.url);
+                     }
+                     else {
+
+                         genre.save(function (err) {
+                           if (err) { return next(err); }
+                           // Genre saved. Redirect to genre detail page.
+                           res.redirect(genre.url);
+                         });
+
+                     }
+
+                 });
+        }
+    }
+];
+ +

The first thing to note is that instead of being a single middleware function (with arguments (req, res, next)) the controller specifies an array of middleware functions. The array is passed to the router function and each method is called in order.

+ + + +
+

Note: This approach is needed, because the sanitisers/validators are middleware functions.

+
+ +

The first method in the array defines a validator (body) to check that the name field is not empty (calling trim() to remove any trailing/leading whitespace before performing the validation). The  second method in the array (sanitizeBody()) creates a sanitizer to trim() the name field and escape() any dangerous  HTML characters.

+ +
// Validate that the name field is not empty.
+body('name', 'Genre name required').isLength({ min: 1 }).trim(),
+
+// Sanitize (trim and escape) the name field.
+sanitizeBody('name').trim().escape(),
+ + + +
+

Note: Sanitizers run during validation do not modify the request. That is why we have to call trim() in both steps above!

+
+ +

After specifying the validators and sanitizers we create a middleware function to extract any validation errors. We use isEmpty() to check whether there are any errors in the validation result. If there are then we render the form again, passing in our sanitised genre object and the array of error messages (errors.array()).

+ +
// Process request after validation and sanitization.
+(req, res, next) => {
+
+    // Extract the validation errors from a request.
+    const errors = validationResult(req);
+
+    // Create a genre object with escaped and trimmed data.
+    var genre = new Genre(
+      { name: req.body.name }
+    );
+
+    if (!errors.isEmpty()) {
+        // There are errors. Render the form again with sanitized values/error messages.
+        res.render('genre_form', { title: 'Create Genre', genre: genre, errors: errors.array()});
+    return;
+    }
+    else {
+        // Data from form is valid.
+        ... <save the result> ...
+    }
+}
+ +

If the genre name data is valid then we check if a Genre with the same name already exists (as we don't want to create duplicates). If it does we redirect to the existing genre's detail page. If not, we save the new Genre and redirect to its detail page.

+ +
// Check if Genre with same name already exists.
+Genre.findOne({ 'name': req.body.name })
+    .exec( function(err, found_genre) {
+    if (err) { return next(err); }
+        if (found_genre) {
+            // Genre exists, redirect to its detail page.
+            res.redirect(found_genre.url);
+            }
+        else {
+            genre.save(function (err) {
+                if (err) { return next(err); }
+                    // Genre saved. Redirect to genre detail page.
+                    res.redirect(genre.url);
+                });
+        }
+});
+ +

This same pattern is used in all our post controllers: we run validators, then sanitisers,  then check for errors and either re-render the form with error information or save the data. 

+ +

View

+ +

The same view is rendered in both the GET and POST controllers/routes when we create a new Genre (and later on it is also used when we updateGenre). In the GET case the form is empty and we just pass a title variable. In the POST case the user has previously entered invalid data—in the genre variable we pass back a sanitized version of the entered data and in the errors variable we pass back an array of error messages.

+ +
res.render('genre_form', { title: 'Create Genre'});
+res.render('genre_form', { title: 'Create Genre', genre: genre, errors: errors.array()});
+ +

Create /views/genre_form.pug and copy in the text below.

+ +
extends layout
+
+block content
+  h1 #{title}
+
+  form(method='POST' action='')
+    div.form-group
+      label(for='name') Genre:
+      input#name.form-control(type='text', placeholder='Fantasy, Poetry etc.' name='name' value=(undefined===genre ? '' : genre.name))
+    button.btn.btn-primary(type='submit') Submit
+
+  if errors
+    ul
+      for error in errors
+        li!= error.msg
+ +

Much of this template will be familiar from our previous tutorials. First we extend the layout.pug base template and override the block named 'content'. We then have a heading with the title we passed in from the controller (via the render() method).

+ +

Next we have the pug code for our HTML form that uses the POST method to send the data to the server, and because the action is an empty string, will send the data to the same URL as the page.

+ +

The form defines a single required field of type "text" called "name". The default value of the field depends on whether the genre variable is defined. If called from the GET route it will be empty as this is a new form. If called from a POST route it will contain the (invalid) value originally entered by the user.

+ +

The last part of the page is the error code. This simply prints a list of errors, if the error variable has been defined (in other words, this section will not appear when the template is rendered on the GET route).

+ +
+

Note: This is just one way to render the errors. You can also get the names of the affected fields from the error variable, and use these to control where the error messages are rendered, whether to apply custom CSS, etc.

+
+ +

What does it look like?

+ +

Run the application, open your browser to http://localhost:3000/, then select the Create new genre link. If everything is set up correctly, your site should look something like the following screenshot. After you enter a value, it should be saved and you'll be taken to the genre detail page.

+ +

Genre Create Page - Express Local Library site

+ +

The only error we validate against server-side is that the genre field must not be empty. The screenshot below shows what the error list would look like if you didn't supply a genre (highlighted in red).

+ +

+ +
+

Note: Our validation uses trim() to ensure that whitespace is not accepted as a genre name. We can also validate that the field is not empty on the client side by adding the value required='true' to the field definition in the form:

+ +
input#name.form-control(type='text', placeholder='Fantasy, Poetry etc.' name='name' value=(undefined===genre ? '' : genre.name), required='true' )
+
+ +

Next steps

+ + + +
+ + + + + +
diff --git a/files/zh-tw/learn/server-side/express_nodejs/forms/delete_author_form/index.html b/files/zh-tw/learn/server-side/express_nodejs/forms/delete_author_form/index.html new file mode 100644 index 0000000000..f26b87bce7 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/forms/delete_author_form/index.html @@ -0,0 +1,167 @@ +--- +title: Delete Author form +slug: Learn/Server-side/Express_Nodejs/forms/Delete_author_form +translation_of: Learn/Server-side/Express_Nodejs/forms/Delete_author_form +--- +

 

+ +

此子文檔展示,如何定義頁面以刪除 Author對象。

+ +

正如表單設計部分所討論的那樣,我們的策略是,只允許刪除“未被其他對象引用” 的對象(在這種情況下,這意味著如果作者Author被一本書Book引用,我們將不允許刪除作者)。在實現方面,這意味著,表單需要在刪除作者之前,先確認沒有關聯的書籍。如果存在關聯的書籍,則應顯示它們,並說明在刪除Author對象之前,必須刪除它們。

+ +

Controller—get route

+ +

Open /controllers/authorController.js. Find the exported author_delete_get() controller method and replace it with the following code.

+ +
// Display Author delete form on GET.
+exports.author_delete_get = function(req, res, next) {
+
+    async.parallel({
+        author: function(callback) {
+            Author.findById(req.params.id).exec(callback)
+        },
+        authors_books: function(callback) {
+          Book.find({ 'author': req.params.id }).exec(callback)
+        },
+    }, function(err, results) {
+        if (err) { return next(err); }
+        if (results.author==null) { // No results.
+            res.redirect('/catalog/authors');
+        }
+        // Successful, so render.
+        res.render('author_delete', { title: 'Delete Author', author: results.author, author_books: results.authors_books } );
+    });
+
+};
+ +

The controller gets the id of the Author instance to be deleted from the URL parameter (req.params.id). It uses the async.parallel() method to get the author record and all associated books in parallel. When both operations have completed it renders the author_delete.pug view, passing variables for the title, author, and author_books.

+ +
+

Note: If  findById() returns no results the author is not in the database. In this case there is nothing to delete, so we immediately render the list of all authors. 

+ +
}, function(err, results) {
+    if (err) { return next(err); }
+    if (results.author==null) { // No results.
+        res.redirect('/catalog/authors')
+    }
+
+ +

Controller—post route

+ +

Find the exported author_delete_post() controller method, and replace it with the following code.

+ +
// Handle Author delete on POST.
+exports.author_delete_post = function(req, res, next) {
+
+    async.parallel({
+        author: function(callback) {
+          Author.findById(req.body.authorid).exec(callback)
+        },
+        authors_books: function(callback) {
+          Book.find({ 'author': req.body.authorid }).exec(callback)
+        },
+    }, function(err, results) {
+        if (err) { return next(err); }
+        // Success
+        if (results.authors_books.length > 0) {
+            // Author has books. Render in same way as for GET route.
+            res.render('author_delete', { title: 'Delete Author', author: results.author, author_books: results.authors_books } );
+            return;
+        }
+        else {
+            // Author has no books. Delete object and redirect to the list of authors.
+            Author.findByIdAndRemove(req.body.authorid, function deleteAuthor(err) {
+                if (err) { return next(err); }
+                // Success - go to author list
+                res.redirect('/catalog/authors')
+            })
+        }
+    });
+};
+ +

First we validate that an id has been provided (this is sent via the form body parameters, rather than using the version in the URL). Then we get the author and their associated books in the same way as for the GET route. If there are no books then we delete the author object and redirect to the list of all authors. If there are still books then we just re-render the form, passing in the author and list of books to be deleted.

+ +
+

Note: We could check if the call to findById() returns any result, and if not,  immediately render the list of all authors.  We've left the code as it is above for brevity (it will still return the list of authors if the id is not found, but this will happen after findByIdAndRemove()).

+
+ +

View

+ +

Create /views/author_delete.pug and copy in the text below.

+ +
extends layout
+
+block content
+  h1 #{title}: #{author.name}
+  p= author.lifespan
+
+  if author_books.length
+
+    p #[strong Delete the following books before attempting to delete this author.]
+
+    div(style='margin-left:20px;margin-top:20px')
+
+      h4 Books
+
+      dl
+      each book in author_books
+        dt
+          a(href=book.url) #{book.title}
+        dd #{book.summary}
+
+  else
+    p Do you really want to delete this Author?
+
+    form(method='POST' action='')
+      div.form-group
+        input#authorid.form-control(type='hidden',name='authorid', required='true', value=author._id )
+
+      button.btn.btn-primary(type='submit') Delete
+ +

The view extends the layout template, overriding the block named content. At the top it displays the author details. It then includes a conditional statement based on the number of author_books (the if and else clauses).

+ + + +

Add a delete control

+ +

Next we will add a Delete control to the Author detail view (the detail page is a good place from which to delete a record).

+ +
+

Note: In a full implementation the control would be made visible only to authorised users. However at this point we haven't got an authorisation system in place!

+
+ +

Open the author_detail.pug view and add the following lines at the bottom.

+ +
hr
+p
+  a(href=author.url+'/delete') Delete author
+ +

The control should now appear as a link, as shown below on the Author detail page.

+ +

+ +

What does it look like?

+ +

Run the application and open your browser to http://localhost:3000/. Then select the All authors link, and then select a particular author. Finally select the Delete author link.

+ +

If the author has no books, you'll be presented with a page like this. After pressing delete, the server will delete the author and redirect to the author list.

+ +

+ +

If the author does have books, then you'll be presented with a view like the following. You can then delete the books from their detail pages (once that code is implemented!).

+ +

+ +
+

Note: The other pages for deleting objects can be implemented in much the same way. We've left that as a challenge.

+
+ +

Next steps

+ + diff --git a/files/zh-tw/learn/server-side/express_nodejs/forms/index.html b/files/zh-tw/learn/server-side/express_nodejs/forms/index.html new file mode 100644 index 0000000000..008d7ae4e8 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/forms/index.html @@ -0,0 +1,274 @@ +--- +title: 'Express 教學 6: 使用表單' +slug: Learn/Server-side/Express_Nodejs/forms +translation_of: Learn/Server-side/Express_Nodejs/forms +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Displaying_data", "Learn/Server-side/Express_Nodejs/deployment", "Learn/Server-side/Express_Nodejs")}}
+ +

在此教程中,我們會教你如何使用 Express ,並且結合 Pug 來實現 HTML 表單,並且如何從數據庫中創建、更新、和刪除文檔。

+ + + + + + + + + + + + +
前提條件:完成前面所有的教程,包括 Express 教程第5章: 展示圖書館數據。
目標:了解如何編寫表單獲取用戶信息,並且將這些數據更新到數據庫中。
+ +

概覽

+ +

HTML 表單是網頁中由一個、或多個字段/小工具形成的一個組合,它被用來收集用戶的信息,並將信息上傳到服務器。表單作為一種用來收集用戶的機制,非常的靈活,因為有各種合適的輸入框,來接受各種類型的數據——文本框,複選框,單選按鈕,時間選擇器等。表單和服務器交互數據也相對安全,因為它使用POST請求發送數據,保護不受跨站點請求偽造攻擊(cross-site request forgery)的威脅。

+ +

但是表單同樣也很複雜!開發者需要編寫給表單編寫 HTML,在服務器上驗證,並且正確去除有害的數據(瀏覽器上也可能需要),對於任何不合法的字段,需要傳給用戶相應的錯誤信息,當數據成功提交後,處理數據,並設法通知用戶提交成功。

+ +

此教程將展示上述的操作,如何在 Express 中實現。在此過程中,我們將擴展 LocalLibrary 網站,以允許用戶創建、編輯、和刪除圖書館中的項目。

+ +
+

注意: 我們還沒有考慮如何將特定路由,限制為經過身份驗證或授權的用戶,因此在這個時間點,任何用戶都可以對數據庫進行更改。

+
+ +

HTML 表單

+ +

首先簡要概述 HTML 表單。考慮一個簡單的 HTML 表單,其中包含一個文本字段,用於輸入某些 “團隊” 的名稱,及其相關標籤:

+ +

Simple name field example in HTML form

+ +

表單在HTML中,定義為 <form>...</form>標記內的元素集合,包含至少一個type="submit"input輸入元素。

+ +
<form action="/team_name_url/" method="post">
+    <label for="team_name">Enter name: </label>
+    <input id="team_name" type="text" name="name_field" value="Default name for team.">
+    <input type="submit" value="OK">
+</form>
+ +

雖然這裡,我們只包含一個(文本)字段,用於輸入團隊名稱,但表單可能包含任意數量的其他輸入元素,及其相關標籤。字段的 type 屬性,定義將顯示哪種窗口小部件。該字段的名稱nameid ,用於標識JavaScript/CSS/HTML 中的字段,而 value定義字段首次顯示時的初始值。匹配團隊標籤使用 label 標籤,指定(請參閱上面的“輸入名稱” "Enter name"),其中 for 字段,包含 input 相關輸入的 id值。

+ +

提交輸入(submit)將顯示為按鈕(默認情況下) - 用戶可以按此按鈕,將其他輸入元素包含的數據,上傳到服務器(在本例中,只有 team_name)。表單屬性,定義用於發送數據的HTTP method方法,和服務器上數據的目標(action):

+ + + +

表單處理流程

+ +

表單處理使用的技術,與我們學習過、用來顯示有關模型的信息的所有技術,是相同的:路由將我們的請求發送到控制器函數,該函數執行所需的任何數據庫操作,包括從模型中讀取數據,然後生成並返回 HTML 頁面。使事情變得更複雜的是,服務器還需要能夠處理用戶提供的數據,並在出現任何問題時,重新顯示帶有錯誤信息的表單。

+ +

下面顯示了處理表單請求的流程圖,從包含表單的頁面請求開始(以綠色顯示):

+ +

+ +

如上圖所示,構成處理代碼所需要做的主要是:  

+ +
    +
  1. 在用戶第一次請求時顯示默認表單。 +
      +
    • 表單可能包含空白字段(例如,如果您正在創建新記錄),或者可能預先填充了初始值(例如,如果您要更改記錄,或者俱有有用的默認初始值)。
    • +
    +
  2. +
  3. 接收用戶提交的數據,通常是在HTTP POST請求中。
  4. +
  5. 驗證並清理數據。
  6. +
  7. 如果任何數據無效,請重新顯示表單 - 這次使用用戶填寫的任何值,和問題字段的錯誤消息。
  8. +
  9. 如果所有數據都有效,請執行所需的操作(例如,將數據保存在數據庫中,發送通知電子郵件,返回搜索結果,上傳文件等)
  10. +
  11. 完成所有操作之後,將用戶重定向到另一個頁面。
  12. +
+ +

表格處理代碼,通常使用 GET路由,以實現表單的初始顯示,以及 POST路由到同一路徑,以處理表單數據的驗證和處理。這是將在本教程中使用的方法!

+ +

Express 本身不提供表單處理操作的任何特定支持,但它可以使用中間件,以處理表單中的 POSTGET參數,並驗證/清理它們的值。

+ +

驗證和清理

+ +

在儲存表單中的數據之前,必須對其進行驗證和清理:

+ + + +

在本教程中,我們將使用流行的 express-validator 模塊,來執行表單數據的驗證和清理。

+ +

安裝

+ +

通過在項目的根目錄中,運行以下命令,來安裝模塊。

+ +
npm install express-validator
+
+ +

使用 express-validator

+ +
+

注意: Github上的 express-validator 指南,提供了API的良好概述。我們建議您閱讀該內容,以了解其所有功能(包括創建自定義驗證程序)。下面我們只介紹一個對 LocalLibrary 有用的子集。

+ +

 

+ +

 

+
+ +

要在我們的控制器中使用驗證器,我們必須從 'express-validator/check'和'express-validator/filter'模塊中,導入我們想要使用的函數,如下所示:

+ +
const { body,validationResult } = require('express-validator/check');
+const { sanitizeBody } = require('express-validator/filter');
+
+ +

有許多可用的功能,允許您一次檢查和清理請求參數,正文,標頭,cookie 等數據,或所有數據。對於本教程,我們主要使用 bodysanitizeBody,和 validationResult(如上面 required 導入的 )。

+ +

功能定義如下:

+ + + +

驗證和清理鏈,是應該傳遞給 Express 路由處理程序的中間件(我們通過控制器,間接地執行此操作)。中間件運行時,每個驗證器/清理程序都按指定的順序運行。

+ +

當我們實現下面的LocalLibrary表單時,我們將介紹一些真實的例子。

+ +

表單設計

+ +

圖書館中的許多模型都是相關/依賴的 - 例如,一本書需要一個作者,也可能有一個或多個種類。這提出了一個問題,即我們應該如何處理用戶希望的情況:

+ + + +

在這個項目,我們為了簡化實作,將聲明表單只能:

+ + + +
+

注意: 更“牢固”的實現,可能允許您在創建新對象時,創建依賴對象,並隨時刪除任何對象(例如,通過刪除依賴對象,或從數據庫中,刪除對已刪除對象的引用) 。

+
+ +

路由

+ +

為了實現我們的表單處理代碼,我們需要兩個具有相同 URL 模式的路由。

+ +

第一個(GET)路由,用於顯示用於創建對象的新空表單。第二個路由(POST),用於驗證用戶輸入的數據,然後保存信息,並重定向到詳細信息頁面(如果數據有效),或重新顯示有錯誤的表單(如果數據無效)。

+ +

我們已經在 /routes/catalog.js(在之前的教程中)為我們所有模型的創建頁面,創建了路徑。例如,種類路由如下所示:

+ +
// GET request for creating a Genre. NOTE This must come before route that displays Genre (uses id).
+router.get('/genre/create', genre_controller.genre_create_get);
+
+// POST request for creating Genre.
+router.post('/genre/create', genre_controller.genre_create_post);
+
+ +

Express 表單子文件

+ +

以下子文件,將帶我們完成向示例應用程序添加所需表單的過程。在進入下一個文件之前,您需要依次閱讀並解決每個問題。

+ +
    +
  1. 創建種類表單 — 定義我們的頁面以創建種類對象 Genre
  2. +
  3. 創建作者表單 — 定義用於創建作者對象 Author 的頁面。
  4. +
  5. 創建書本表單 — 定義頁面/表單以創建書本對象 Book
  6. +
  7. 創建書本實例表單 — 定義頁面/表單以創建書本實例對象 BookInstance
  8. +
  9. 刪除作者表單 — 定義要刪除作者對象 Author 的頁面。
  10. +
  11. 更新書本表單 — 定義頁面以更新書本對象 Book
  12. +
+ +

挑戰自我

+ +

實現 Book, BookInstance, 和 Genre模型的刪除頁面,用跟我們的作者刪除頁面相同的方式,將它們與關聯的詳細信息頁面,鏈接起來。頁面應遵循相同的設計方法:

+ + + +

一些提示:

+ + + +

實現 BookInstance, Author, 和 Genre模型的更新頁面,以與我們的書本更新頁面相同的方式,將它們與關聯的詳細信息頁面,鏈接起來。

+ +

一些提示:

+ + + +

總結

+ +

Express, node, 與NPM上面的第三方套件,提供你需要的每樣東西 ,可用於新增表單到你的網站上。在本文中,您學習如何使用 Pug 創建表單,使用 express-validator 驗證和清理輸入,以及添加,刪除和修改數據庫中的記錄。

+ +

你現在應該了解如何新增基本表單,以及表單處理代碼到你的 node 網站!

+ +

請參閱

+ + + +

{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Displaying_data", "Learn/Server-side/Express_Nodejs/deployment", "Learn/Server-side/Express_Nodejs")}}

+ +

本教程連結

+ + + +

 

diff --git a/files/zh-tw/learn/server-side/express_nodejs/index.html b/files/zh-tw/learn/server-side/express_nodejs/index.html new file mode 100644 index 0000000000..c1c6e11ee5 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/index.html @@ -0,0 +1,73 @@ +--- +title: Express web framework (Node.js/JavaScript) +slug: Learn/Server-side/Express_Nodejs +tags: + - Express + - Express.js + - Node + - node.js + - 介紹 + - 伺服器端程式 + - 初學者 + - 學習 +translation_of: Learn/Server-side/Express_Nodejs +--- +
{{LearnSidebar}}
+ +

Express 是一個流行的web框架,使用JavsScript實現,執行在node.js環境上。本系列解釋Express的優點、如何設定開發環境、完成常見的web開發和佈署。

+ +

前置需求

+ +

在開始前你需要了解什麼是伺服器端web程式和什麼是web框架,推薦閱讀伺服器端網站開發第一步。建議了解基本的程式知識和JavaScript,但不需要知道核心概念。

+ +
+

注意: 本網站有許多學習JavaScript應用在客戶端開發的有用資源,如:JavaScriptJavaScript 指南JavaScript 基礎JavaScript (learning)。使用Node.js開發伺服器端使用的JavaScript語言與概念和客戶端是一樣的。Node.js提供額外的APIs以支援無瀏覽器環境,例如:建立HTTP服務和讀取檔案系統。但不支援DOM及瀏覽器相關的 JavaScript API。

+ +

這份指南將提供一些使用Node.js和Express的資訊以及數個優秀的學習資源。部分連結由 How do I get started with Node.js(StackOverflow) 與 What are the best resources for learning Node.js?(Quora) 提供。

+
+ +

指南

+ +
+
Express/Node 介紹
+
第一篇的系列文章中回答了「什麼是Node」和「什麼是Express?」並概略的說明為什麼Express web框架如此特別。此文章將重點放在主要的功能上,並展示一些Express應用常見的建構模塊(儘管此時你還沒有可供測試的開發環境)
+
設定 Node (Express) 開發環境
+
現在你已經了解Express的目的了,接下來繼續說明如何設定和測試 Windows、Linux (Ubuntu)和Mac OS X上的Node/Express開發環境。不管你用的是什麼作業系統,你都能在本文中找到開發Express應用的入門需知。
+
Express 教學(1): The Local Library website
+
在第一篇實務教學系列文章中將說明你將會學到什麼?以及提供範例網站local library的概覽,我們將在後續的文章中繼續改進它。
+
Express 教學(2): 建構網站骨架
+
本文章展示如何建構網站的骨架,接著你可以自己添加路由、模板/畫面和資料庫。
+
Express 教學(3): 使用資料庫(以Mongoose為例)
+
本文簡短的介紹Node/Express如何使用資料庫。接下來展示LocalLibray網站如何透過Mongoose進行資料庫的存取。說明物件綱要(object schema)和模型(models)如何宣告、the main field types和基本驗證。同時簡單的展示幾個讀取資料的主要方法。
+
Express 教學(4): 路由和控制器
+
在本教學中,我們將為LocalLibrary網站中的所有資源終端設定“虛擬”處理函數的路由(URL處理代碼)。 完成後,我們將為我們的路由處理程式提供模組化結構,以便我們可以在後續的教學中擴展真正的處理函數。 我們也將了解如何使用Express創建模組化路由。
+
Express 教學(5): 顯示圖書館的資料
+
現在已經準備好新增頁面來展示館藏和其他資料了。這些頁面包括一個展示我們有多少種model 型態的首頁、所有models的列表和詳細資料頁面。透過本教學你可以得到從資料庫取得紀錄和使用模板的實務經驗。
+
Express 教學(6): 使用表單
+
本教學中展示如何使用Express的插件-Pug來使用HTML Forms,以及如何編寫表單來創造、更新和刪除資料庫的文件。
+
Express 教學(7): 網站佈署
+
現在你完成了很棒的LocalLibrary 網站,你希望圖書館的員工和會員可以透過網路讀取它。本教學概略說明如何找到主機來佈署你的網站以及為了使你的網站正式上線所需做的準備。
+
+ +

或許你也想看

+ +
+
在 PWS/Cloud Foundry上安裝LocalLibrary
+
本文展示如何在Pivotal Web Services PaaS cloud上安裝LocalLibrary ,PWS/Cloud Foundry是一個完整且開源的Heroku替代品,可使用於教學(7)。如果你正在尋找Heroku或其他PaaS的替代品或只是想玩點不同的東西,那PWS/Cloud Foundry絕對值得一試。
+
+ +

新增其他教學

+ +
+

現在已經有了很多教學,但你可能會想寫其他有趣主題的模塊,包括:

+ + + +

當然,如果能作個評估模塊就更好了!

+
diff --git a/files/zh-tw/learn/server-side/express_nodejs/introduction/index.html b/files/zh-tw/learn/server-side/express_nodejs/introduction/index.html new file mode 100644 index 0000000000..6fc3f0a98c --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/introduction/index.html @@ -0,0 +1,522 @@ +--- +title: Express/Node introduction +slug: Learn/Server-side/Express_Nodejs/Introduction +tags: + - Express + - Node + - nodejs + - 伺服器端 + - 初學者 + - 學習 +translation_of: Learn/Server-side/Express_Nodejs/Introduction +--- +
+ + + + +

{{LearnSidebar}}

+ +

{{NextMenu("Learn/Server-side/Express_Nodejs/development_environment", "Learn/Server-side/Express_Nodejs")}}

+
+ +

在這篇文章中回答了「什麼是Node?」和「什麼是Express」,同時概述是什麼讓Express框架如此特別。本文將概述主要特性、展示一些Express應用的主要建構模塊(雖然此時你還沒有能測試它的開發環境)

+ + + + + + + + + + + + +
前置需求:基本的電腦知識。 對伺服器端網站程式設計的基本了解,特別是網站中客戶端 - 伺服器交互的機制
目標:提升對Express的了解、如何與Node搭配使用、提供的功能和Express應用的主要建構模塊。
+ +

什麼是Express和Node?

+ +

Node (或者說Node.js) 是一個開源、跨平台和允許開發者使用Javascript創造伺服器端工具和應用的執行環境。運行的目的是為了能在瀏覽器外使用,例如:直接執行在電腦或伺服器上。所以該環境捨棄了瀏覽器限定的JavaScript APIs並增加更多傳統OS APIs的支援,例如:HTTP和檔案系統的程式庫。

+ + + +

從網站伺服器開發的觀點來看Node有幾項優點:

+ + + +

你可以只用Node的HTTP模組創造一個簡單的web伺服器來回應任何請求,如下所示。此教學不會告訴建議的檔案名稱或如何執行該檔案 ;-)

+ +

這將創造一個伺服器並會監聽http://127.0.0.1:8000/上任何種類的HTTP請求,當接收到任何請求時回傳一個「Hello World」的純文字回應。

+ +
// 載入 HTTP 模組
+var http = require("http");
+
+// 創建 HTTP 伺服器並監聽8000 port
+http.createServer(function(request, response) {
+
+   // Set the response HTTP header with HTTP status and Content type
+   response.writeHead(200, {'Content-Type': 'text/plain'});
+
+   // Send the response body "Hello World"
+   response.end('Hello World\n');
+}).listen(8000);
+
+// Print URL for accessing server
+console.log('Server running at http://127.0.0.1:8000/');
+ +

Node並不原生支持其他常見的web開發任務,如果你想為不同的HTTP方法(例如:GET, POST, DELETE等)增加特定的處理、替不同的URL路徑提供靜態檔案、使用樣板或動態性的產生response,你需要自己完成相關的程式或者是避免重新造輪子 - 使用web框架!

+ +

Express 是最受歡迎的Node web框架,還是其他許多流行的Node web框架的底層庫,它提供:

+ + + +

雖然Express本身非常簡單,但開發者們已經創造相容的中間層套件來解決大部份web開發的問題,這些套件能處理cookies, sessions,登入,URL參數,POST資料,安全標頭等等,你能在Express Middleware中找到這些套件的列表(以及其他流行的第三方套件)

+ +
+

注意: 這種靈活性是一把雙刃劍。有一些中間層套件能解決大部份的問題或需求,但使用正確的套件有時會是一個問題。也沒有「正確的方法」來創建應用,你在網路上找到的範例也並非都是最佳解或是只有開發上所需要做的一小部份。

+
+ +

歷史

+ +

2009年Node在Linux平台上初次發佈. 2010年NPM套件管利器發佈, 2012年增加Windows的原生支援. 現在的LTS版本為Node v8.11.2,最新版本為Node v10.1.0。這只是它深厚歷史的一小片斷,欲知更多詳情請洽 Wikipedia

+ +

2010年11月Express初次發佈,現在的API版本為 4.16。你可以查閱更新紀錄來了解此版本做了甚麼更改或是從GitHub中了解詳細的歷史紀錄。

+ +

Node/Express有多流行?

+ +

對於web 框架而言流行度很重要,這代表他會不會被繼續更新、文件、附加套件和技術支援方面有多少資源

+ +

現在沒有一個明確的指標來評斷伺服器端框架的流行度,雖然有 Hot Frameworks透過計算GitHub的專案數量和StackOverflow的問題來衡量流行度。更好的問題是,Node和Express是否「夠流行」以避免成為不流行的平台。有沒有持續進步?需要時是否能得到幫助?能不能找到Express相關的工作?

+ +

從眾多使用Express的公司、貢獻程式碼的人數和那些提供免費/收費支援的人員來看,是的!Express是一個流行的框架。

+ +

Is Express opinionated?

+ +

Web 框架通常自稱為 "opinionated" 或 "unopinionated".

+ +

Opinionated指的是那些有「正確」方法解決特定問題的框架。在特定的需求上他們通常能快速開發,因為正確的方法通常易懂且有良好的文件,然而在面對其他問題時則會失去靈活性。這類型的框架通常傾向於提供較少的選擇和套件來解決問題。

+ +

反過來說Unopinionated 框架,對於如何組合套件來解決問題尚有較少的限制,開發者可以更輕易的使用適當的套件來解決特定問題,儘管代價是你需要自己找到適合的套件。

+ +

Express是Unopinionated 框架,你可以在request處理流程中使用任何相容套件,使用單一或複數個檔案來建構應用,有時候甚至會覺得擁有太多選擇了。

+ +

Express的程式碼長怎樣?

+ +

傳統的資料驅動網站中,web應用程式會等待來自瀏覽器(或其他客戶端)的HTTP Request,接收到Request後根據URL和可能夾帶的POST/GET資料來決定需要回應什麼動作,根據需要可能對資料庫進行讀寫或執行滿足Request所需的其他任務。web應用程式會回應Response給瀏覽器,通常是藉由插入檢所到的資料到HTML 模板中動態產生HTML頁面讓瀏覽器顯示。

+ + + +

Express provides methods to specify what function is called for a particular HTTP verb (GET, POST, SET, etc.) and URL pattern ("Route"), and methods to specify what template ("view") engine is used, where template files are located, and what template to use to render a response. You can use Express middleware to add support for cookies, sessions, and users, getting POST/GET parameters, etc. You can use any database mechanism supported by Node (Express does not define any database-related behaviour).

+ +

The following sections explain some of the common things you'll see when working with Express and Node code.

+ +

Helloworld Express

+ +

First lets consider the standard Express Hello World example (we discuss each part of this below, and in the following sections).

+ +
+

Tip: If you have Node and Express already installed (or if you install them as shown in the next article), you can save this code in a text file called app.js and run it in a bash command prompt by calling:   

+ +

./node ./app.js

+
+ +
var express = require('express');
+var app = express();
+
+app.get('/', function(req, res) {
+  res.send('Hello World!');
+});
+
+app.listen(3000, function() {
+  console.log('Example app listening on port 3000!');
+});
+
+ +

The first two lines require() (import) the express module and create an Express application. This object, which is traditionally named app, has methods for routing HTTP requests, configuring middleware, rendering HTML views, registering a template engine, and modifying application settings that control how the application behaves (e.g. the environment mode, whether route definitions are case sensitive, etc.)

+ +

The middle part of the code (the three lines starting with app.get) shows a route definition. The app.get() method specifies a callback function that will be invoked whenever there is an HTTP GET request with a path ('/') relative to the site root. The callback function takes a request and a response object as arguments, and simply calls send() on the response to return the string "Hello World!"

+ +

The final block starts up the server on port '3000' and prints a log comment to the console. With the server running, you could go to localhost:3000 in your browser to see the example response returned.

+ +

Importing and creating modules

+ +

A module is a JavaScript library/file that you can import into other code using Node's require() function. Express itself is a module, as are the middleware and database libraries that we use in our Express applications.

+ +

The code below shows how we import a module by name, using the Express framework as an example. First we invoke the require() function, specifying the name of the module as a string ('express'), and calling the returned object to create an Express application. We can then access the properties and functions of the application object.

+ +
var express = require('express');
+var app = express();
+
+ +

You can also create your own modules that can be imported in the same way.

+ +
+

Tip: You will want to create your own modules, because this allows you to organise your code into managable parts — a monolithic single-file application is hard to understand and maintain. Using modules also helps you manage your namespace, because only the variables you explicitly export are imported when you use a module.

+
+ +

To make objects available outside of a module you just need to assign them to the exports object. For example, the square.js module below is a file that exports area() and perimeter() methods:

+ +
exports.area = function(width) { return width * width; };
+exports.perimeter = function(width) { return 4 * width; };
+
+ +

We can import this module using require(), and then call the exported method(s) as shown:

+ +
var square = require('./square'); // Here we require() the name of the file without the (optional) .js file extension
+console.log('The area of a square with a width of 4 is ' + square.area(4));
+ +
+

Note: You can also specify an absolute path to the module (or a name, as we did initially).

+
+ +

If you want to export a complete object in one assignment instead of building it one property at a time, assign it to module.exports as shown below (you can also do this to make the root of the exports object a constructor or other function):

+ +
module.exports = {
+  area: function(width) {
+    return width * width;
+  },
+
+  perimeter: function(width) {
+    return 4 * width;
+  }
+};
+
+ +

For a lot more information about modules see Modules (Node API docs).

+ +

Using asynchronous APIs

+ +

JavaScript code frequently uses asynchronous rather than synchronous APIs for operations that may take some time to complete. A synchronous API is one in which each operation must complete before the next operation can start. For example, the following log functions are synchronous, and will print the text to the console in order (First, Second).

+ +
console.log('First');
+console.log('Second');
+
+ +

By contrast, an asynchronous API is one in which the API will start an operation and immediately return (before the operation is complete). Once the operation finishes, the API will use some mechanism to perform additional operations. For example, the code below will print out "Second, First" because even though setTimeout() method is called first, and returns immediately, the operation doesn't complete for several seconds.

+ +
setTimeout(function() {
+   console.log('First');
+   }, 3000);
+console.log('Second');
+
+ +

Using non-blocking asynchronous APIs is even more important on Node than in the browser, because Node is a single threaded event-driven execution environment. "single threaded" means that all requests to the server are run on the same thread (rather than being spawned off into separate processes). This model is extremely efficient in terms of speed and server resources, but it does mean that if any of your functions call synchronous methods that take a long time to complete, they will block not just the current request, but every other request being handled by your web application.

+ +

There are a number of ways for an asynchronous API to notify your application that it has completed. The most common way is to register a callback function when you invoke the asynchronous API, that will be called back when the operation completes. This is the approach used above.

+ +
+

Tip: Using callbacks can be quite "messy" if you have a sequence of dependent asynchronous operations that must be performed in order, because this results in multiple levels of nested callbacks. This problem is commonly known as "callback hell". This problem can be reduced by good coding practices (see http://callbackhell.com/), using a module like async, or even moving to ES6 features like Promises.

+
+ +
+

Note: A common convention for Node and Express is to use error-first callbacks. In this convention the first value in your callback functions is an error value, while subsequent arguments contain success data. There is a good explanation of why this approach is useful in this blog: The Node.js Way - Understanding Error-First Callbacks (fredkschott.com).

+
+ +

Creating route handlers

+ +

In our Hello World Express example (see above), we defined a (callback) route handler function for HTTP GET requests to the site root ('/').

+ +
app.get('/', function(req, res) {
+  res.send('Hello World!');
+});
+
+ +

The callback function takes a request and a response object as arguments. In this case the method simply calls send() on the response to return the string "Hello World!" There are a number of other response methods for ending the request/response cycle, for example you could call res.json() to send a JSON response or res.sendFile() to send a file.

+ +
+

JavaScript tip: You can use any argument names you like in the callback functions; when the callback is invoked the first argument will always be the request and the second will always be the response. It makes sense to name them such that you can identify the object you're working with in the body of the callback.

+
+ +

The Express application object also provides methods to define route handlers for all the other HTTP verbs, which are mostly used in exactly the same way: post(), put(), delete(), options(), trace(), copy(), lock(), mkcol(), move(), purge(), propfind(), proppatch(), unlock(), report(), mkactivity(), checkout(), merge(), m-search(), notify(), subscribe(), unsubscribe(), patch(), search(), and connect().

+ +

There is a special routing method, app.all(), which will be called in response to any HTTP method. This is used for loading middleware functions at a particular path for all request methods. The following example (from the Express documentation) shows a handler that will be executed for requests to /secret irrespective of the HTTP verb used (provided it is supported by the http module).

+ +
app.all('/secret', function(req, res, next) {
+  console.log('Accessing the secret section ...');
+  next(); // pass control to the next handler
+});
+ +

Routes allow you to match particular patterns of characters in a URL, and extract some values from the URL and pass them as parameters to the route handler (as attributes of the request object passed as a parameter).

+ +

Often it is useful to group route handlers for a particular part of a site together and access them using a common route-prefix (e.g. a site with a Wiki might have all wiki-related routes in one file and have them accessed with a route prefix of /wiki/). In Express this is achieved by using the express.Router object. For example, we can create our wiki route in a module named wiki.js, and then export the Router object, as shown below:

+ +
// wiki.js - Wiki route module
+
+var express = require('express');
+var router = express.Router();
+
+// Home page route
+router.get('/', function(req, res) {
+  res.send('Wiki home page');
+});
+
+// About page route
+router.get('/about', function(req, res) {
+  res.send('About this wiki');
+});
+
+module.exports = router;
+
+ +
+

Note: Adding routes to the Router object is just like adding routes to the app object (as shown previously).

+
+ +

To use the router in our main app file we would then require() the route module (wiki.js), then call use() on the Express application to add the Router to the middleware handling path. The two routes will then be accessible from /wiki/ and /wiki/about/.

+ +
var wiki = require('./wiki.js');
+// ...
+app.use('/wiki', wiki);
+ +

We'll show you a lot more about working with routes, and in particular about using the Router, later on in the linked section Routes and controllers .

+ +

Using middleware

+ +

Middleware is used extensively in Express apps, for tasks from serving static files to error handling, to compressing HTTP responses. Whereas route functions end the HTTP request-response cycle by returning some response to the HTTP client, middleware functions typically perform some operation on the request or response and then call the next function in the "stack", which might be more middleware or a route handler. The order in which middleware is called is up to the app developer.

+ +
+

Note: The middleware can perform any operation, execute any code, make changes to the request and response object, and it can also end the request-response cycle. If it does not end the cycle then it must call next() to pass control to the next middleware function (or the request will be left hanging).

+
+ +

Most apps will use third-party middleware in order to simplify common web development tasks like working with cookies, sessions, user authentication, accessing request POST and JSON data, logging, etc. You can find a list of middleware packages maintained by the Express team (which also includes other popular 3rd party packages). Other Express packages are available on the NPM package manager.

+ +

To use third party middleware you first need to install it into your app using NPM. For example, to install the morgan HTTP request logger middleware, you'd do this:

+ +
$ npm install morgan
+
+ +

You could then call use() on the Express application object to add the middleware to the stack:

+ +
var express = require('express');
+var logger = require('morgan');
+var app = express();
+app.use(logger('dev'));
+...
+ +
+

Note: Middleware and routing functions are called in the order that they are declared. For some middleware the order is important (for example if session middleware depends on cookie middleware, then the cookie handler must be added first). It is almost always the case that middleware is called before setting routes, or your route handlers will not have access to functionality added by your middleware.

+
+ +

You can write your own middleware functions, and you are likely to have to do so (if only to create error handling code). The only difference between a middleware function and a route handler callback is that middleware functions have a third argument next, which middleware functions are expected to call if they are not that which completes the request cycle (when the middleware function is called, this contains the next function that must be called).

+ +

You can add a middleware function to the processing chain with either app.use() or app.add(), depending on whether you want to apply the middleware to all responses or to responses with a particular HTTP verb (GET, POST, etc). You specify routes the same in both cases, though the route is optional when calling app.use().

+ +

The example below shows how you can add the middleware function using both methods, and with/without a route.

+ +
var express = require('express');
+var app = express();
+
+// An example middleware function
+var a_middleware_function = function(req, res, next) {
+  // ... perform some operations
+  next(); // Call next() so Express will call the next middleware function in the chain.
+}
+
+// Function added with use() for all routes and verbs
+app.use(a_middleware_function);
+
+// Function added with use() for a specific route
+app.use('/someroute', a_middleware_function);
+
+// A middleware function added for a specific HTTP verb and route
+app.get('/', a_middleware_function);
+
+app.listen(3000);
+ +
+

JavaScript Tip: Above we declare the middleware function separately and then set it as the callback. In our previous route handler function we declared the callback function when it was used. In JavaScript, either approach is valid.

+
+ +

The Express documentation has a lot more excellent documentation about using and writing Express middleware.

+ +

Serving static files

+ +

You can use the express.static middleware to serve static files, including your images, CSS and JavaScript (static() is the only middleware function that is actually part of Express). For example, you would use the line below to serve images, CSS files, and JavaScript files from a directory named 'public' at the same level as where you call node:

+ +
app.use(express.static('public'));
+
+ +

Any files in the public directory are served by adding their filename (relative to the base "public" directory) to the base URL. So for example:

+ +
http://localhost:3000/images/dog.jpg
+http://localhost:3000/css/style.css
+http://localhost:3000/js/app.js
+http://localhost:3000/about.html
+
+ +

You can call static() multiple times to serve multiple directories. If a file cannot be found by one middleware function then it will simply be passed on to the subsequent middleware (the order that middleware is called is based on your declaration order).

+ +
app.use(express.static('public'));
+app.use(express.static('media'));
+
+ +

You can also create a virtual prefix for your static URLs, rather than having the files added to the base URL. For example, here we specify a mount path so that the files are loaded with the prefix "/media":

+ +
app.use('/media', express.static('public'));
+
+ +

Now, you can load the files that are in the public directory from the /media path prefix.

+ +
http://localhost:3000/media/images/dog.jpg
+http://localhost:3000/media/video/cat.mp4
+http://localhost:3000/media/cry.mp3
+
+ +

For more information, see Serving static files in Express.

+ +

Handling errors

+ +

Errors are handled by one or more special middleware functions that have four arguments, instead of the usual three: (err, req, res, next). For example:

+ +
app.use(function(err, req, res, next) {
+  console.error(err.stack);
+  res.status(500).send('Something broke!');
+});
+
+ +

These can return any content required, but must be called after all other app.use() and routes calls so that they are the last middleware in the request handling process!

+ +

Express comes with a built-in error handler, which takes care of any remaining errors that might be encountered in the app. This default error-handling middleware function is added at the end of the middleware function stack. If you pass an error to next() and you do not handle it in an error handler, it will be handled by the built-in error handler; the error will be written to the client with the stack trace.

+ +
+

Note: The stack trace is not included in the production environment. To run it in production mode you need to set the the environment variable NODE_ENV to 'production'.

+
+ +
+

Note: HTTP404 and other "error" status codes are not treated as errors. If you want to handle these, you can add a middleware function to do so. For more information see the FAQ.

+
+ +

For more information see Error handling (Express docs).

+ +

Using databases

+ +

Express apps can use any database mechanism supported by Node (Express itself doesn't define any specific additional behaviour/requirements for database management). There are many options, including PostgreSQL, MySQL, Redis, SQLite, MongoDB, etc.

+ +

In order to use these you have to first install the database driver using NPM. For example, to install the driver for the popular NoSQL MongoDB you would use the command:

+ +
$ npm install mongodb
+
+ +

The database itself can be installed locally or on a cloud server. In your Express code you require the driver, connect to the database, and then perform create, read, update, and delete (CRUD) operations. The example below (from the Express documentation) shows how you can find "mammal" records using MongoDB.

+ +
//this works with older versions of  mongodb version ~ 2.2.33
+var MongoClient = require('mongodb').MongoClient;
+
+MongoClient.connect('mongodb://localhost:27017/animals', function(err, db) {
+  if (err) throw err;
+
+  db.collection('mammals').find().toArray(function (err, result) {
+    if (err) throw err;
+
+    console.log(result);
+  });
+});
+
+
+//for mongodb version 3.0 and up
+let MongoClient = require('mongodb').MongoClient;
+MongoClient.connect('mongodb://localhost:27017/animals', function(err, client){
+   if(err) throw err;
+
+   let db = client.db('animals');
+   db.collection('mammals').find().toArray(function(err, result){
+     if(err) throw err;
+     console.log(result);
+     client.close();
+   });
+}
+
+ + + + + + + +

Another popular approach is to access your database indirectly, via an Object Relational Mapper ("ORM"). In this approach you define your data as "objects" or "models" and the ORM maps these through to the underlying database format. This approach has the benefit that as a developer you can continue to think in terms of JavaScript objects rather than database semantics, and that there is an obvious place to perform validation and checking of incoming data. We'll talk more about databases in a later article.

+ +

For more information see Database integration (Express docs).

+ +

Rendering data (views)

+ +

Template engines (referred to as "view engines" by Express) allow you to specify the structure of an output document in a template, using placeholders for data that will be filled in when a page is generated. Templates are often used to create HTML, but can also create other types of documents. Express has support for a number of template engines, and there is a useful comparison of the more popular engines here: Comparing JavaScript Templating Engines: Jade, Mustache, Dust and More.

+ +

In your application settings code you set the template engine to use and the location where Express should look for templates using the 'views' and 'view engines' settings, as shown below (you will also have to install the package containing your template library too!)

+ +
var express = require('express');
+var app = express();
+
+// Set directory to contain the templates ('views')
+app.set('views', path.join(__dirname, 'views'));
+
+// Set view engine to use, in this case 'some_template_engine_name'
+app.set('view engine', 'some_template_engine_name');
+
+ +

The appearance of the template will depend on what engine you use. Assuming that you have a template file named "index.<template_extension>" that contains placeholders for data variables named 'title' and "message", you would call Response.render() in a route handler function to create and send the HTML response:

+ +
app.get('/', function(req, res) {
+  res.render('index', { title: 'About dogs', message: 'Dogs rock!' });
+});
+ +

For more information see Using template engines with Express (Express docs).

+ +

File structure

+ +

Express makes no assumptions in terms of structure or what components you use. Routes, views, static files, and other application-specific logic can live in any number of files with any directory structure. While it is perfectly possible to have the whole Express application in one file, typically it makes sense to split your application into files based on function (e.g. account management, blogs, discussion boards) and architectural problem domain (e.g. model, view or controller if you happen to be using an MVC architecture).

+ +

In a later topic we'll use the Express Application Generator, which creates a modular app skeleton that we can easily extend for creating web applications.

+ + + +

總結

+ +

恭喜,您已完成 Express / Node之旅的第一步!您現在應該了解 Express 和 Node 的主要優點,以及 Express 應用程序的主要部分(路由,中間件,錯誤處理和模板代碼)。您還應該明白,Express 是一個不固執己見的框架,您將這些組件組合在一起的方式以及您使用的函式庫,在很大程度上取決於您!

+ +

當然,Express是一個非常輕量級的 Web 應用程序框架,它的許多好處和潛力來自第三方函式庫和功能。我們將在以下文章中更詳細地介紹這些內容。在下一篇文章中,我們將介紹如何設置 Node 開發環境,以便您可以開始查看一些 Express 代碼。

+ +

See also

+ + + +
{{NextMenu("Learn/Server-side/Express_Nodejs/development_environment", "Learn/Server-side/Express_Nodejs")}}
+ +

In this module

+ + diff --git a/files/zh-tw/learn/server-side/express_nodejs/mongoose/index.html b/files/zh-tw/learn/server-side/express_nodejs/mongoose/index.html new file mode 100644 index 0000000000..8541c1c37c --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/mongoose/index.html @@ -0,0 +1,792 @@ +--- +title: 'Express 教學 3: 使用資料庫 ( Mongoose)' +slug: Learn/Server-side/Express_Nodejs/mongoose +translation_of: Learn/Server-side/Express_Nodejs/mongoose +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/skeleton_website", "Learn/Server-side/Express_Nodejs/routes", "Learn/Server-side/Express_Nodejs")}}
+ +

本文簡短介紹數據庫,以及如何搭配 Node / Express 應用,使用數據庫。接下來會演示我們如何使用 Mongoose,為本地圖書館提供數據庫存取。本文說明物件要求與模型如何宣告,主要的欄位型態,以及基本驗證。本文也簡短演示一些存取模型數據的主要方法。

+ + + + + + + + + + + + +
前置條件:Express 教學 2: 創建一個骨架網站
目標:能夠使用Mongoose設計並創造自己的模型。
+ +

概覽

+ +

圖書館職員會使用本地圖書館網站,存放書本和借書者訊息。圖書館使用者會用網站瀏覽與尋找書本,看看是否有可以藉閱的書本複本,然後預約或者藉閱。為了有效率地存放與取用訊息,我們將把它存放到數據庫。

+ +

Express 應用可以使用許多不同的數據庫,並且有好幾種方法可以執行創建 Create、讀取 Read、更新 Update 和刪除 Delete (CRUD) 操作。本教程為一些可用的選項,提供簡短的概覽,然後接著詳細演示該選項的特定運行機制。

+ +

我可以使用什麼數據庫?

+ +

Express 應用程序可以使用 Node 支持的任何數據庫(Express 本身不會為數據庫管理,定義任何特定的附加行為/要求)。有許多流行的選項,包括 PostgreSQL,MySQL,Redis,SQLite 和 MongoDB。

+ +

在選擇數據庫時,您應該考慮時間 - 生產力/學習曲線,性能,易複製/備份,成本,社區支持等等。雖然沒有單一的 “最佳” 數據庫,但幾乎任何流行的解決方案,我們的本地圖書館這樣的中小型網站,應該都可以接受。

+ +

有關選項的更多訊息,請參閱:數據庫集成(Express docs)

+ +

與數據庫互動的最好方式是什麼?

+ +

有兩種與數據庫互動的方法:

+ + + +

通過使用 SQL 或數據庫支持的任何查詢語言,都可以獲得最佳性能。 ODM通常比較慢,因為它們使用翻譯代碼,在對象和數據庫格式之間進行映射,這可能不會使用最有效的數據庫查詢(尤其是如果ODM支持不同的數據庫後端,並且必須在各個數據庫所支持的功能方面,做出更大的折衷)。

+ +

使用 ORM 的好處是,程序員可以繼續用 JavaScript 對象而不是數據庫語義來思考 — 如果您需要使用不同數據庫(在相同或不同的網站上),那麼尤其如此。他們還提供了一個明顯的地方來執行數據驗證和檢查。

+ +
+

提示:  使用ODM / ORM通常可以降低開發和維護成本!除非您非常熟悉本地查詢語言,或者性能對您至關重要,否則您應該強烈考慮使用 ODM。

+
+ +

我應該使用哪個 ORM/ODM ?

+ +

NPM 套件管理器站點上,有許多ODM / ORM 解決方案(查看 odmorm 標籤的子集合!)。

+ +

在撰寫本文時,受歡迎的幾種解決方案是:   

+ + + +

一般來說,在選擇解決方案時,您應該考慮提供的功能和 “社區活動” (下載,貢獻,錯誤報告,文檔質量等)。在撰寫本文時,Mongoose 是迄今為止最受歡迎的 ODM,如果您將MongoDB 用於你的數據庫,那麼它是一個合理的選擇。

+ +

在本地圖書館使用 Mongoose 和 MongoDb

+ +

對於本地圖書館示例(以及本主題的其餘部分),我們將使用 Mongoose ODM 來訪問我們的圖書館數據。 Mongoose 是 MongoDB 的前端,MongoDB 是一個使用面向文檔數據模型的開源 NoSQL 數據庫。在 MongoDB 數據庫中,“文檔” 的 “集合” ,類似於關係數據庫中 “行” 的 “表”。

+ +

這種 ODM 和數據庫的結合在 Node 社區中非常流行,部分原因是文檔存儲和查詢系統,看起來非常像 JSON,因此對 JavaScript 開發人員來說很熟悉。

+ +
+

提示: 使用 Mongoose 時,您不需要事先了解 MongoDB,但是如果您已經熟悉 MongoDB,Mongoose documentation 文檔的一部分會更易於使用和理解。

+
+ +

本教程的其餘部分,將介紹如何為 本地圖書館網站示例,定義和訪問Mongoose 模式和模型。

+ +

設計本地圖書館的模型

+ +

在您開始編寫模型之前,花幾分鐘的時間思考,我們需要儲存的數據以及不同對象之間的關係。

+ +

我們知道,我們需要儲存有關書籍的訊息(標題,摘要,作者,種類,國際標準書號),以及我們可能有多個副本可用(具有全域唯一ID,可用狀態等)。我們可能需要存儲有關作者的更多訊息,而不僅僅是他們的名字,並且可能有多個作者,具有相同或相似的名稱。我們希望能夠根據書名,作者,種類和類別對訊息進行分類。

+ +

在設計模型時,對於每個“對象”(相關訊息組)都有獨立的模型,是有意義的。在這種情況下,明顯的對像是書籍,書籍實例和作者。

+ +

您可能還希望,使用模型來表示選擇列表選項(例如,選擇的下拉列表),而不是將選項硬編碼到網站本身— 在無法預先知道所有選項,或者可能更改時,更建議使用模型來表示。很明顯的,書本類型是這種模型的可能人選(例如科幻小說,法國詩歌等)。

+ +

一旦我們決定了我們的模型和字段,我們就需要考慮它們之間的關係。

+ +

考慮到這一點,下面的UML關聯圖,顯示了我們在這種情況下定義的模型(一個框對應一個模型)。如上所述,我們創建了以下模型,圖書(本書的通用細節),書本實例(系統中可用圖書的特定實際副本的狀態)和作者。我們還決定建立一個種類模型,以便可以動態創建它的值,而不是將下拉選項硬編碼。我們已經決定不為書本實例:狀態BookInstance:status建立模型—我們將硬編碼可接受的值,因為我們不希望這些值發生變化。在下圖每個框中,您可以看到模型名稱,字段名稱和類型,以及方法及其返回類型。

+ +

下圖還顯示了模型之間的關係,包括它們的多重性。多重性是圖中顯示可能存在於關係中的每個模型的數量(最大值和最小值)的數字。例如,框之間的連接線,顯示書本Book和種類Genre是相關的。靠近書本Book模型的數字,表明一本書必須有零個或多個種類(您想要多少都可以),而種類Genre旁邊一行的數字,表明它可以有零個或多個相關書籍。

+ +
+

注意: 正如我們在下面的Mongoose入門中所討論的那樣,通常只需要在一個模型中定義文檔/模型之間關係的字段(通過在另一個模型中搜索相關的_id仍然可以找到反向關係)。下面我們選擇在書本綱要(Book schema)中定義Book/Genre和Book/Author之間的關係,以及書本實例綱要(BookInstance Schema)中Book/BookInstance之間的關係。這種選擇有點武斷—我們同樣可以在其他綱要中擁有該字段。

+
+ +

Mongoose Library Model  with correct cardinality

+ +
+

注意 :下一節提供了一個基本的入門知識,解釋如何定義和使用模型。在您閱讀它時,請想想我們將如何構建上圖中的每個模型。

+
+ +

Mongoose入門

+ +

本節概述如何將Mongoose 連接到MongoDB 數據庫,如何定義模型綱要和模型,以及如何進行基本查詢。

+ +
+

注意:本入門受到npm上的Mongoose快速入門Mongoose官方文檔的“深度影響”。

+
+ +

安裝Mongoose和MongoDB

+ +

Mongoose像任何其他依賴項一樣,安裝在您的項目(package.json)中—使用NPM。要安裝它,請在項目文件夾中,使用以下命令:

+ +
npm install mongoose
+
+ +

安裝Mongoose會添加所有依賴項,包括MongoDB數據庫驅動程序,但它不會安裝MongoDB 。如果你想安裝一個MongoDB服務器,那麼你可以從這裡下載各種操作系統的安裝程序,並在本地安裝。您還可以使用基於雲端的MongoDB實例。

+ +
+

注意:對於本教程,我們將使用基於mLab雲的數據庫,作為服務沙箱層來提供數據庫。這適用於開發,也對於本教程很有意義,因為它使“安裝”與操作系統無關(數據庫即服務,也是您可能會用於生產環境數據庫的一種方法)。

+
+ +

連接到MongoDB

+ +

Mongoose需要連接到MongoDB數據庫。您可以require()並使用mongoose.connect(),以連接到本地託管的數據庫,如下所示。

+ +
//Import the mongoose module
+var mongoose = require('mongoose');
+
+//Set up default mongoose connection
+var mongoDB = 'mongodb://127.0.0.1/my_database';
+mongoose.connect(mongoDB);
+// Get Mongoose to use the global promise library
+mongoose.Promise = global.Promise;
+//Get the default connection
+var db = mongoose.connection;
+
+//Bind connection to error event (to get notification of connection errors)
+db.on('error', console.error.bind(console, 'MongoDB connection error:'));
+ +

您可以使用mongoose.connection獲取默認的Connection對象。一旦連接,在Connection實例上,將觸發打開事件。

+ +
+

提示:如果需要創建其他連接,可以使用mongoose.createConnection()這與connect()採用相同形式的數據庫URI(包含主機,數據庫,端口,選項等),並返回Connection對象。

+
+ +

定義並創建模型

+ +

模型使用Schema接口進行定義。Schema允許您定義存儲在每個文檔中的字段,及其驗證要求和默認值。此外,您可以定義靜態和實例助手方法,以更輕鬆地處理數據類型,以及可以像其他任何字段一樣使用的虛擬屬性,但實際上並不存儲在數據庫中(我們稍後將討論)。

+ +

然後,綱要Schemas被mongoose.model()方法“編譯”為模型。擁有模型後,您可以使用它來查找,創建,更新和刪除給定類型的對象。

+ +
+

注意:每個模型都映射到MongoDB數據庫中的文檔集合。這些文檔將包含模型綱要Schema中定義的字段/綱要型態。

+
+ +

定義綱要Schemas

+ +

下面的代碼片段,顯示了您可以如何定義一個簡單的綱要。首先require()mongoose,然後使用Schema構造函數,創建一個新的Schema實例,在構造函數的對象參數中,定義其中的各個字段。

+ +
//Require Mongoose
+var mongoose = require('mongoose');
+
+//Define a schema
+var Schema = mongoose.Schema;
+
+var SomeModelSchema = new Schema({
+    a_string: String,
+    a_date: Date
+});
+
+ +

在上面的例子中,我們只有兩個字段,一個字符串和一個日期。在接下來的部分中,我們將展示一些其他的字段類型,驗證和其他方法。

+ +

創建模型

+ +

使用mongoose.model()方法從綱要創建模型:

+ +
// Define schema
+var Schema = mongoose.Schema;
+
+var SomeModelSchema = new Schema({
+    a_string: String,
+    a_date: Date
+});
+
+// Compile model from schema
+var SomeModel = mongoose.model('SomeModel', SomeModelSchema );
+ +

第一個參數,是將為模型創建的集合的單數名稱(Mongoose將為上面的SomeModel模型,創建數據庫集合),第二個參數,是您要在創建模型時使用的綱要Shema。

+ +
+

注意:定義模型類後,可以使用它們來創建,更新或刪除記錄,並運行查詢,以獲取記錄的所有記錄,或特定子集。我們將在以下“使用模型”部分,向您展示如何執行上述操作,以及當創建視圖時,如何執行此操作。

+
+ +

綱要型態(字段)

+ +

綱要schema可以有任意數量的字段 — 每個字段代表存儲在MongoDB 文檔中的字段。如下的示例綱要,顯示許多常見字段類型及其聲明方式。

+ +
var schema = new Schema(
+{
+  name: String,
+  binary: Buffer,
+  living: Boolean,
+  updated: { type: Date, default: Date.now },
+  age: { type: Number, min: 18, max: 65, required: true },
+  mixed: Schema.Types.Mixed,
+  _someId: Schema.Types.ObjectId,
+  array: [],
+  ofString: [String], // You can also have an array of each of the other types too.
+  nested: { stuff: { type: String, lowercase: true, trim: true } }
+})
+ +

大多數綱要型態SchemaTypes(“type:”之後或字段名稱之後的描述符)都是自解釋的。例外情況是:

+ + + +

該代碼還顯示了聲明一個字段的兩種方式:

+ + + +

有關選項的更多訊息,請參閱SchemaTypes(Mongoose docs)。

+ +

驗證

+ +

Mongoose 提供內置和自定義驗證器,以及同步和異步驗證器。它允許您在所有情況下,指定可接受的範圍或值,以及驗證失敗的錯誤消息。

+ +

內置的驗證器包括:

+ + + +

下面的示例(從Mongoose文檔稍微修改)顯示瞭如何指定一些驗證器類型和錯誤消息:

+ +

+    var breakfastSchema = new Schema({
+      eggs: {
+        type: Number,
+        min: [6, 'Too few eggs'],
+        max: 12
+        required: [true, 'Why no eggs?']
+      },
+      drink: {
+        type: String,
+        enum: ['Coffee', 'Tea', 'Water',]
+      }
+    });
+
+ +

有關字段驗證的完整訊息,請參閱驗證(Mongoose docs)。

+ +

虛擬屬性

+ +

虛擬屬性是您可以獲取和設置的文檔屬性,但不會持久保存到MongoDB。getter 對格式化或組合字段非常有用,而setter 可用於將單個值分解為多個值,以進行存儲。

+ +

文檔中的示例,從名字和姓氏字段構造(並解構)一個全名虛擬屬性,這比每次在模板中使用全名更簡單,更清晰。

+ +
+

注意:我們將使用庫中的虛擬屬性,來為每個使用路徑和記錄的_id值的模型記錄,定義唯一的URL。

+
+ +

欲了解更多訊息,請參閱虛擬(Mongoose文檔)。

+ +

方法和查詢幫助

+ +

綱要schema也可以有實例方法靜態方法查詢助手實例和靜態方法很相似,但有明顯的區別,即實例方法與特定記錄相關聯,並且可以訪問當前對象。查詢助手允許您擴展mongoose的鍊式查詢構建器API(例如,除了find(), findOne()findById()方法外,還允許您添加一個“byName”查詢。

+ +

使用模型

+ +

一旦創建了綱要,就可以使用它來創建模型。該模型代表數據庫中可以搜索的文檔集合,而模型的實例代表您可以保存和檢索的單個文檔。

+ +

我們在下面簡要介紹一下。有關更多訊息,請參閱:模型(Mongoose docs)。

+ +

創建和修改文檔

+ +

要創建記錄,您可以定義模型的實例,然後調用save()下面的例子假設,SomeModel是我們從綱要創建的模型(帶有單一字段“name” )。

+ +
// Create an instance of model SomeModel
+var awesome_instance = new SomeModel({ name: 'awesome' });
+
+// Save the new model instance, passing a callback
+awesome_instance.save(function (err) {
+  if (err) return handleError(err);
+  // saved!
+});
+
+ +

創建記錄(以及更新,刪除和查詢)是異步操作— 您提供在操作完成時調用的回調。API使用錯誤優先參數約定,因此回調的第一個參數將始終為錯誤值(或null)。如果API返回一些結果,則將作為第二個參數提供。

+ +

您還可以使用create(),同時定義模型實例,並保存模型實例。回調將為第一個參數返回錯誤,為第二個參數返回新創建的模型實例。

+ +
SomeModel.create({ name: 'also_awesome' }, function (err, awesome_instance) {
+  if (err) return handleError(err);
+  // saved!
+});
+ +

每個模型都有一個關聯的連接(當您使用mongoose.model()時,這將成為默認連接)。您創建一個新連接並調用.model(),以在另一個數據庫上創建文檔。

+ +

您可以使用點語法訪問此新記錄中的字段,並更改值。您必須調用save()update(),將修改的值存回數據庫。

+ +
// Access model field values using dot notation
+console.log(awesome_instance.name); //should log 'also_awesome'
+
+// Change record by modifying the fields, then calling save().
+awesome_instance.name="New cool name";
+awesome_instance.save(function (err) {
+   if (err) return handleError(err); // saved!
+   });
+
+ +

尋找紀錄

+ +

可以使用查詢方法搜索記錄,將查詢條件指定為JSON 文檔。下面的代碼片段,顯示瞭如何在數據庫中,找到所有參加網球運動的運動員,只返回運動員姓名和年齡的字段。這裡我們只指定一個匹配的字段(運動 sport),但您可以添加更多條件,指定正則表達式標準,或完全刪除條件以返回所有運動員。

+ +
var Athlete = mongoose.model('Athlete', yourSchema);
+
+// find all athletes who play tennis, selecting the 'name' and 'age' fields
+Athlete.find({ 'sport': 'Tennis' }, 'name age', function (err, athletes) {
+  if (err) return handleError(err);
+  // 'athletes' contains the list of athletes that match the criteria.
+})
+ +

如果您指定回調,如上所示,查詢將立即執行。搜索完成後將調用回調。

+ +
+

注意: Mongoose中的所有回調,都使用此回調模式callback(error, result)如果執行查詢時發生錯誤,錯誤參數error將包含錯誤文檔,並且結果result將為null。如果查詢成功,則error參數將為null,並且結果result 將被填充到查詢結果。

+
+ +

如果您未指定回調,則API將返回Query類型的變量。您可以使用此查詢對象來構建查詢,然後稍後使用exec()方法執行(使用回調)。

+ +
// find all athletes that play tennis
+var query = Athlete.find({ 'sport': 'Tennis' });
+
+// selecting the 'name' and 'age' fields
+query.select('name age');
+
+// limit our results to 5 items
+query.limit(5);
+
+// sort by age
+query.sort({ age: -1 });
+
+// execute the query at a later time
+query.exec(function (err, athletes) {
+  if (err) return handleError(err);
+  // athletes contains an ordered list of 5 athletes who play Tennis
+})
+ +

上面我們在find()方法中,定義了查詢條件。我們也可以使用where()函數來執行此操作,並且我們可以使用點運算符( . )將查詢的所有部分鏈接在一起,而不是分別添加它們。

+ +

下面的代碼片段,與我們上面的查詢相同,並有年齡的附加條件。

+ +
Athlete.
+  find().
+  where('sport').equals('Tennis').
+  where('age').gt(17).lt(50).  //Additional where query
+  limit(5).
+  sort({ age: -1 }).
+  select('name age').
+  exec(callback); // where callback is the name of our callback function.
+ +

find()  方法獲取所有匹配的記錄,但通常你只想獲得一個匹配。以下方法可以查詢單個記錄:

+ + + +
+

注意:還有一個count()方法,您可以使用它來獲取與條件匹配的項目數。如果您想要在不實際提取記錄的情況下執行計數,這非常有用。

+
+ +

查詢可以做更多的事情。有關更多訊息,請參閱:查詢(Mongoose文檔)。

+ +

運用相關文檔— population方法

+ +

您可以使用ObjectId綱要字段,從一個文檔/模型實例,創建一對一引用,或者使用ObjectIds數組,從一個文檔創建一對多的引用。該字段存儲相關模型的ID。如果需要關聯文檔的實際內容,可以在查詢中使用populate()方法,將id替換為實際數據。

+ +

例如,以下綱要定義作者和故事。每個作者可以有多個故事,我們將其表示為一個ObjectId數組。每個故事可以有一個作者。綱要從“ref”(以粗體突出顯示)得知,可以分配給該字段的模型。

+ +
var mongoose = require('mongoose')
+  , Schema = mongoose.Schema
+
+var authorSchema = Schema({
+  name    : String,
+  stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
+});
+
+var storySchema = Schema({
+  author : { type: Schema.Types.ObjectId, ref: 'Author' },
+  title    : String
+});
+
+var Story  = mongoose.model('Story', storySchema);
+var Author = mongoose.model('Author', authorSchema);
+ +

我們可以通過分配_id值,來保存對相關文檔的引用。下面我們創建一個作者,然後創建一個故事,並將作者ID分配給我們的故事作者字段。

+ +
var bob = new Author({ name: 'Bob Smith' });
+
+bob.save(function (err) {
+  if (err) return handleError(err);
+
+  //Bob now exists, so lets create a story
+  var story = new Story({
+    title: "Bob goes sledding",
+    author: bob._id    // assign the _id from the our author Bob. This ID is created by default!
+  });
+
+  story.save(function (err) {
+    if (err) return handleError(err);
+    // Bob now has his story
+  });
+});
+ +

我們的故事文檔,現在有作者文檔ID引用的作者。為了在我們的故事結果中,獲取作者訊息,我們使用populate(),如下所示。

+ +
Story
+.findOne({ title: 'Bob goes sledding' })
+.populate('author') //This populates the author id with actual author information!
+.exec(function (err, story) {
+  if (err) return handleError(err);
+  console.log('The author is %s', story.author.name);
+  // prints "The author is Bob Smith"
+});
+ +
+

注意:敏銳的讀者會注意到,我們在故事中添加了作者,但我們沒有做任何事情,來將我們的故事添加到作者的故事stories數組中。那麼我們怎樣才能得到特定作者的所有故事?

+ +

一種方法,是將作者添加到故事數組中,但這會導致我們需要在兩個地方,維護與作者和故事有關的訊息。更好的方法是獲取作者的_id,然後使用find(),在所有故事的作者字段中搜索此內容。

+ +
Story
+.find({ author : bob._id })
+.exec(function (err, stories) {
+  if (err) return handleError(err);
+  // returns all stories that have Bob's id as their author.
+});
+
+
+ +

這幾乎是您在本教程中,使用相關項目時,需要了解的所有內容。有關更多詳細訊息,請參閱Population(Mongoose docs)。

+ +

一個檔案對應一個綱要/模型

+ +

雖然您可以使用任何喜歡的文件結構創建綱要和模型,但我們強烈建議在每個模型模塊(文件)中,定義每個模型綱要,導出方法以創建模型。如下所示:

+ +
// File: ./models/somemodel.js
+
+//Require Mongoose
+var mongoose = require('mongoose');
+
+//Define a schema
+var Schema = mongoose.Schema;
+
+var SomeModelSchema = new Schema({
+    a_string          : String,
+    a_date            : Date,
+});
+
+//Export function to create "SomeModel" model class
+module.exports = mongoose.model('SomeModel', SomeModelSchema );
+ +

然後,您可以在其他文件中,立即要求並使用該模型。下面我們展示如何使用它,來獲取模型的所有實例。

+ +
//Create a SomeModel model just by requiring the module
+var SomeModel = require('../models/somemodel')
+
+// Use the SomeModel object (model) to find all SomeModel records
+SomeModel.find(callback_function);
+ +

架設MongoDB數據庫

+ +

現在我們了解了Mongoose能做什麼,以及我們想如何設計我們的模型,現在該開始在LocalLibrary網站上工作了。我們想要做的第一件事,就是設置一個MongoDb數據庫,我們可以使用它來儲存我們的圖書館數據。

+ +

本教程,我們將使用mLab免費的雲託管的“ 沙盒 ”數據庫。這個數據庫層不適合生產環境的網站,因為它沒有冗餘設計,但它對於開發和原型設計來說非常有用。我們在這裡使用它,是因為它免費且易於設置,並且因為作為數據庫服務供應商來說,mLab是流行的數據庫選擇之一,您可能會合理選擇您的生產環境數據庫(撰寫本文時,其他流行的選擇包括ComposeScaleGridMongoDB Atlas)。

+ +
+

注意:如果您願意,可以下載並安裝與系統相對應的二進製文件,在本地設置MongoDb數據庫。除了您在連接時指定的數據庫URL之外,本文中的其餘指令將很類似。

+
+ +

您首先需要使用mLab創建一個賬戶(這是免費的,只需要輸入基本聯繫訊息,並確認其服務條款)。

+ +

登錄後,您將進入mLab主畫面:

+ +
    +
  1. 單擊MongoDB Deployments部分中的Create New。
  2. +
  3. 這將打開“雲提供商”Cloud Provider 選擇畫面。
    + MLab - screen for new deployment
    + +
      +
    • 從“計劃類型”Plan Type 部分中,選擇“SANDBOX(免費)”計劃。
    • +
    • 從“雲提供商” Cloud Provider部分,選擇任意提供商。不同的提供商,提供不同的地區(顯示在選定的計劃類型下面)。
    • +
    • 單擊“繼續” Continue按鈕。
    • +
    +
  4. +
  5. 這將打開“選擇區域” Select Region 畫面。 +

    Select new region screen

    + +
      +
    • +

      選擇離您最近的地區,然後選擇繼續Continue .

      +
    • +
    +
  6. +
  7. +

    這將打開 Final Details 畫面
    + New deployment database name

    + +
      +
    • +

      輸入新數據庫的名稱local_library,然後選擇繼續Continue

      +
    • +
    +
  8. +
  9. +

    這將打開訂單確認畫面。
    + Order confirmation screen

    + +
      +
    • +

      單擊“提交訂單” Submit Order以創建數據庫。

      +
    • +
    +
  10. +
  11. +

    您將返回到主畫面。單擊剛剛創建的新數據庫,以打開其詳細訊息畫面。正如你所看到的,數據庫沒有集合(數據)。
    + mLab - Database details screen
    +  您需要用來訪問數據庫的URL,顯示在上面的表單中(如上圖所示)。為了使用它,您需要創建一個可以在URL中指定的數據庫用戶。

    +
  12. +
  13. 單擊用戶Users選項卡,並選擇添加數據庫用戶按鈕Add database user
  14. +
  15. 輸入用戶名和密碼(兩次),然後按創建Create不要選擇只讀read-only
    +
  16. +
+ +

您現在已經創建了數據庫,並且有一個可以用來訪問它的URL(帶有用戶名和密碼)。這看起來像是這樣的:mongodb://your_user_namer:your_password@ds119748.mlab.com:19748/local_library.

+ +

安裝 Mongoose

+ +

打開命令提示符,並到您創建本地圖書館骨架網站的目錄。輸入以下命令,安裝Mongoose(及其依賴項),並將其添加到您的package.json文件中,除非您在閱讀上述Mongoose入門時,已經這樣做了。

+ +
npm install mongoose
+
+ +

連接到 MongoDB

+ +

打開/app.js(位於項目的根目錄),並在宣告Express應用程序對象的位置(在var app = express();之後)複製以下文本。將數據庫url字符串('insert_your_database_url_here')替換為表示您自己的數據庫的位置URL(即是使用來自上面mLab的訊息)。

+ +
//Set up mongoose connection
+var mongoose = require('mongoose');
+var mongoDB = 'insert_your_database_url_here';
+mongoose.connect(mongoDB);
+mongoose.Promise = global.Promise;
+var db = mongoose.connection;
+db.on('error', console.error.bind(console, 'MongoDB connection error:'));
+ +

正如上面的Mongoose入門中所討論的,此代碼創建了與數據庫的默認連接,並綁定到錯誤事件(以便將錯誤打印到控制台)。

+ +

定義本地圖書館綱要

+ +

如上所述,我們將為每個模型定義一個單獨的模塊。首先在項目根目錄(/models)中,為我們的模型創建一個文件夾,然後為每個模型創建單獨的文件:

+ +
/express-locallibrary-tutorial  //the project root
+  /models
+    author.js
+    book.js
+    bookinstance.js
+    genre.js
+
+ +

作者模型

+ +

複製下面顯示的Author作者綱要代碼,並將其粘貼到./models/author.js文件中。該綱要定義了一個作者,具有StringSchemaTypes的第一個名稱和家族名稱,這是必需的,最多有100個字符,Date字段為出生和死亡日期。

+ +
var mongoose = require('mongoose');
+
+var Schema = mongoose.Schema;
+
+var AuthorSchema = new Schema(
+  {
+    first_name: {type: String, required: true, max: 100},
+    family_name: {type: String, required: true, max: 100},
+    date_of_birth: {type: Date},
+    date_of_death: {type: Date},
+  }
+);
+
+// Virtual for author's full name
+AuthorSchema
+.virtual('name')
+.get(function () {
+  return this.family_name + ', ' + this.first_name;
+});
+
+// Virtual for author's URL
+AuthorSchema
+.virtual('url')
+.get(function () {
+  return '/catalog/author/' + this._id;
+});
+
+//Export model
+module.exports = mongoose.model('Author', AuthorSchema);
+
+
+ +

我們還為AuthorSchema,聲明了一個名為“url”的虛擬屬性,它返回獲取模型的特定實例所需的絕對URL — 每當我們需要獲取指向特定作者的鏈接時,我們將在模板中使用該屬性。

+ +
+

注意:在綱要中聲明我們的URL是虛擬的,這是一個好主意,因為一個項目的URL只需要在一個地方更改。此時,使用此URL的鏈接將不起作用,因為我們還沒有任何路由,可以處理個別模型實例的代碼。我們將在後面的文章中介紹這些內容!

+
+ +

在模塊的最後,我們導出了模型。

+ +

書本模型

+ +

複製下面顯示的Book綱要代碼,並將其粘貼到./models/book.js文件中。其中大部分與作者模型相似—我們已經聲明了一個具有多個字符串字段的綱要,以及一個虛擬屬性,用於獲取特定書籍記錄的URL,並且我們已經導出了模型。

+ +
var mongoose = require('mongoose');
+
+var Schema = mongoose.Schema;
+
+var BookSchema = new Schema(
+  {
+    title: {type: String, required: true},
+    author: {type: Schema.Types.ObjectId, ref: 'Author', required: true},
+    summary: {type: String, required: true},
+    isbn: {type: String, required: true},
+    genre: [{type: Schema.Types.ObjectId, ref: 'Genre'}]
+  }
+);
+
+// Virtual for book's URL
+BookSchema
+.virtual('url')
+.get(function () {
+  return '/catalog/book/' + this._id;
+});
+
+//Export model
+module.exports = mongoose.model('Book', BookSchema);
+
+ +

這裡的主要區別,是我們已經創建了兩個對其他模型的引用:

+ + + +

書本實例模型

+ +

最後,複製下面顯示的BookInstance綱要代碼,並將其粘貼到./models/bookinstance.js文件中。BookInstance表示某人可能藉閱的書籍的特定副本,並包含有關該副本是否可用,或預期返回日期的訊息,“印記”或版本詳細訊息。

+ +
var mongoose = require('mongoose');
+
+var Schema = mongoose.Schema;
+
+var BookInstanceSchema = new Schema(
+  {
+    book: { type: Schema.Types.ObjectId, ref: 'Book', required: true }, //reference to the associated book
+    imprint: {type: String, required: true},
+    status: {type: String, required: true, enum: ['Available', 'Maintenance', 'Loaned', 'Reserved'], default: 'Maintenance'},
+    due_back: {type: Date, default: Date.now}
+  }
+);
+
+// Virtual for bookinstance's URL
+BookInstanceSchema
+.virtual('url')
+.get(function () {
+  return '/catalog/bookinstance/' + this._id;
+});
+
+//Export model
+module.exports = mongoose.model('BookInstance', BookInstanceSchema);
+ +

我們在這裡展示的新東西,是字段選項:

+ + + +

其他所有內容,大夥應該在前面教程裡邊已經熟悉了。

+ +

種類模型-自我挑戰!

+ +

打開你的./models/genre.js文件,並創建一個存儲類型的綱要(書本的類別,例如它是小說還是非小說,浪漫史或軍事歷史等)。

+ +

該定義將與其他模型非常相似:

+ + + +

測試—創建一些項目

+ +

就是這樣。我們現在已經為該網站建立了所有模型!

+ +

為了測試這些模型(並創建一些示例書籍,和其他項目以便於我們在後面文章使用),現在我們將運行一個獨立的腳本來創建每種類型的項目:

+ +
    +
  1. 在express-locallibrary-tutorial目錄下(與package.json處於同一級別),下載(或以其他方式創建)文件populatedb.js + +
    +

    注意:您不需要知道populatedb.js的工作原理;它只是將示例數據添加到數據庫中。

    +
    +
  2. +
  3. 在項目根目錄中,輸入以下命令,以安裝腳本所需的異步模塊(我們將在後面的教程中討論這一點) +
    npm install async
    +
  4. +
  5. 在命令提示符下,使用node運行此腳本,傳遞MongoDB數據庫的URL(與之前在app.js中替換insert_your_database_url_here佔位符的那個相同): +
    node populatedb <your mongodb url>​​​​
    +
  6. +
  7. 該腳本應一路運行至完成,並在終端中創建它們時顯示各項目。
  8. +
+ +
+

提示:mLab上的數據庫。您現在應該可以深入到書本籍,作者,種類和書本實例的各個集合中,並查看單個文檔。

+
+ +

總結

+ +

本文中我們學到了一點數據庫和Node/Express的ORMs,更多的是關於如何定義Mongoose綱要與模型。然後我們使用這些知識,為本地圖書館網站設計並實作出書本Book,書本實例BookInstance,作者Author和種類Genre模型。

+ +

最後,我們創建一些實例,以測試模型(使用獨立運作的命令稿)。下一篇文章,我們將關注於如何創建一些網頁,以呈現這些物件。

+ +

參閱

+ + + +

{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/skeleton_website", "Learn/Server-side/Express_Nodejs/routes", "Learn/Server-side/Express_Nodejs")}}

+ +

本教程連結

+ + diff --git a/files/zh-tw/learn/server-side/express_nodejs/routes/index.html b/files/zh-tw/learn/server-side/express_nodejs/routes/index.html new file mode 100644 index 0000000000..f4549ec598 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/routes/index.html @@ -0,0 +1,646 @@ +--- +title: 'Express 教學 4: 路由與控制器' +slug: Learn/Server-side/Express_Nodejs/routes +translation_of: Learn/Server-side/Express_Nodejs/routes +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/mongoose", "Learn/Server-side/Express_Nodejs/Displaying_data", "Learn/Server-side/Express_Nodejs")}}
+ +

在本教程中,我們將為最終在 本地圖書館 網站中需要的所有資源端點,搭配 "空殼" 處理函式來配置路由 (URL handling code) 。完成後,我們的路由處理源碼將會有模組化結構,在接下來的文章中,我們可以用真實的處理函式加以擴充。我們也會對如何使用Express 創建模組化路由,有更好的理解。

+ + + + + + + + + + + + +
先備知識:閱讀 Express/Node 介紹。 完成先前教學主題 (包含 Express 教學 3: 使用資料庫 (Mongoose)).
目標:理解如何創建簡易路由配置。我們所有的URL端點。
+ +

概覽

+ +

上一篇教程文章中,我們定義了Mongoose模型,以與數據庫互動,並使用(獨立)腳本創建一些初始庫記錄。現在我們可以編寫代碼,向用戶展示這些信息。我們需要做的第一件事,是確定我們希望能夠在頁面中顯示哪些信息,然後定義適當的URL,以返回這些資源。然後我們將需要創建路由(URL處理程序)和視圖(模板)來顯示這些頁面。

+ +

下圖是作為處理HTTP請求/響應時,需要實現的主要數據流和事項的提醒。除了視圖和路線之外,圖表還顯示“控制器” — 實際處理請求的函數,那些與路由請求分開的代碼。

+ +

由於我們已經創建了模型,我們需要創建的主要內容是:

+ + + +

 

+ +

+ +

最終,我們可能會有頁面顯示書籍,流派,作者和書籍的列表和詳細信息,以及用於創建,更新和刪除記錄的頁面。對一篇文章來說,這是很多的內容。因此,本文的大部分內容,都將集中在設置我們的路由和控制器,以返回“虛擬”內容。我們將在後續文章中,擴展控制器方法,以使用模型數據。

+ +

下面的第一部分,提供了關於如何使用Express Router中間件的簡要“入門”。當我們設置LocalLibrary路由時,我們將在後面的章節中使用這些知識。

+ +

路由入門

+ +

路由是Express代碼的一部分,它將HTTP動詞(GET, POST, PUT, DELETE等),URL路徑/模式和被調用來處理該模式的函數,相關聯起來。

+ +

有幾種方法可以創建路線。本教程將使用express.Router中間件,因為它允許我們將站點的特定部分的路由處理程序組合在一起,並使用通用的路由前綴訪問它們。我們會將所有與圖書館有關的路由,保存在“目錄”模塊中,如果我們添加路由來處理用戶帳戶或其他功能,我們可以將它們分開保存。

+ +
+

注意:我們在Express簡介>創建路由處理程序中,簡要討論了Express應用程序路由。除了為模塊化提供更好的支持之外(如下面第一小節所述),使用Router非常類似於直接在Express應用程序對像上定義路由。

+
+ +

本節的其餘部分,概述瞭如何使用路由器Router來定義路由。

+ +

定義和使用單獨的路由模塊

+ +

下面的代碼提供了一個具體示例,說明我們如何創建路由模塊,然後在Express應用程序中使用它。首先,我們在一個名為wiki.js的模塊中創建一個wiki的路由。代碼首先導入Express應用程序對象,使用它獲取一個

+ +

Router對象,然後使用get()方法向其添加一對路由。所有模塊的最後一個導出路由器Router對象。

+ +
// wiki.js - Wiki route module.
+
+var express = require('express');
+var router = express.Router();
+
+// Home page route.
+router.get('/', function (req, res) {
+  res.send('Wiki home page');
+})
+
+// About page route.
+router.get('/about', function (req, res) {
+  res.send('About this wiki');
+})
+
+module.exports = router;
+
+
+ +
+

注意:上面我們直接在路由器函數中定義路由處理程序回調。在LocalLibrary中,我們將在一個單獨的控制器模塊中,定義這些回調。

+
+ +

要在主應用程序文件中使用路由器模塊,我們首先require()路由模塊(wiki.js)。然後,我們在Express應用程序上調用use(),將路由器添加到中間件處理路徑,並指定一個'wiki'的URL路徑。

+ +
var wiki = require('./wiki.js');
+// ...
+app.use('/wiki', wiki);
+ +

然後可以從/wiki//wiki/about/,訪問我們的wiki路由模塊中定義的兩個路由。

+ +

路由函數

+ +

我們上面的模塊,定義了幾個典型的路由功能。使用Router.get()方法定義“about”路由(在下面),該方法僅響應HTTP GET請求。此方法的第一個參數是URL路徑,而第二個參數是一個回調函數,如果收到帶有路徑的HTTP GET請求,將會調用該函數。

+ +
router.get('/about', function (req, res) {
+  res.send('About this wiki');
+})
+
+ +

回調函數接受三個參數(通常如下所示命名:req, res, next),它將包含HTTP請求對象,HTTP響應,以及中間件鏈中的下一個函數。

+ +
+

注意:路由器功能是Express中間件,這意味著它們必須完成(響應)請求或調用鏈中的下一個功能next在上面的例子中,我們使用send()完成了請求,所以下一個參數next沒有被使用(我們選擇不指定它)。

+ +

上面的路由器函數只需要一次回調,但您可以根據需要指定任意數量的回調參數,或一組回調函數。每個函數都是中間件鏈的一部分,並且將按照添加到鏈中的順序調用(除非前面的函數完成請求)。

+ +

 

+
+ +

這裡的回調函數,在響應中調用send(),當我們收到帶有路徑(' /about')的GET請求時,返回字符串“About this wiki”。許多其他響應方法,可以結束請求/響應週期。例如,您可以調用res.json(),來發送JSON響應,或調用res.sendFile()來發送文件。構建庫時,我們最常使用的響應方法是render(),它使用模板和數據創建並返回HTML文件—我們將在後面的文章中,進一步討論這個問題!

+ +

 HTTP 動詞

+ +

上面的示例路由使用Router.get()方法,響應具有特定路徑的HTTP GET請求。路由器Router還為所有其他HTTP動詞提供路由方法,這些方法多數以完全相同的方式使用:post(), put(), delete(), options(), trace(), copy(), lock(), mkcol(), move(), purge(), propfind(), proppatch(), unlock(), report(), mkactivity()​​​​​​, checkout(), merge(), m-search(), notify(), subscribe(), unsubscribe(), patch(), search(),和connect()

+ +

例如,下面的代碼就像上一個/about路由一樣,但只響應HTTP POST請求。

+ +
router.post('/about', function (req, res) {
+  res.send('About this wiki');
+})
+ +

路由路徑

+ +

路由路徑定義可以進行請求的端點。我們到目前為止看到的例子,都是字符串,並且完全按照字符串的寫法使用:'/','/ about','/ book','/any-random.path'。

+ +

路由路徑也可以是字符串模式。字符串模式使用正則表達式語法的子集,來定義將匹配的端點模式。下面列出了子集(請注意,連字符(-)和點(.)由字符串路徑字面解釋):

+ + + +

路由路徑也可以是JavaScript正則表達式例如,下面的路由路徑將與鯰魚catfish 和角鯊魚dogfish相匹配,但不包括鯰魚catflap、鯰魚頭catfishhead等。請注意,正則表達式的路徑使用正則表達式語法(它不像以前那樣,是帶引號的字符串)。

+ +
app.get(/.*fish$/, function (req, res) {
+  ...
+})
+ +
+

注意: LocalLibrary的大部分路由,都只使用字符串,而不是字符串模式和正則表達式。我們還將使用下一節中討論的路由參數。

+
+ +

路由參數

+ +

路徑參數是命名的URL段,用於捕獲在URL中的位置指定的值。命名段以冒號為前綴,然後是名稱(例如。捕獲的值,使用參數名稱作為鍵,存在對像中(例如)。/:your_parameter_name/req.paramsreq.params.your_parameter_name

+ +

例如,考慮一個編碼的URL,其中包含有關用戶和書本的信息:http://localhost:3000/users/34/books/8989我們可以使用userIdbookId路徑參數,提取如下所示的信息:

+ +
app.get('/users/:userId/books/:bookId', function (req, res) {
+  // Access userId via: req.params.userId
+  // Access bookId via: req.params.bookId
+  res.send(req.params);
+})
+
+ +

路由參數的名稱,必須由“單詞字符”(AZ,az,0-9和_)組成。

+ +
+

注意: URL /book/create將與/book/:bookId 之類的路由匹配(它將提取要創建' create'的“bookId”值)。將使用與傳入URL匹配的第一個路由,因此,如果要單獨處理/book/createURL,則必須在/book/:bookId路由之前,先定義其路由處理程序。

+
+ +

這就是您開始使用路由所需的全部內容-如果需要,您可以在Express文檔中找到更多信息:基本路由路由指南以下部分顯示了我們如何為LocalLibrary設置路由和控制器。

+ +

本地圖書館需要的路由

+ +

下面列出了我們最終需要用於頁面的URL,其中object被替換為每個模型的名稱(book,bookinstance,genre,author),objects是對象的複數,id是默認情況下,為每個Mongoose模型實例指定的唯一實例字段(_id)。

+ + + +

第一個主頁和列表頁面,不編碼任何其他信息。雖然返回的結果,將取決於模型類型和數據庫中的內容,但為了獲取信息所運行的查詢,將始終相同(類似地,用於創建對象的代碼將始終類似)。相反的,其他URL用於處理特定文檔/模型實例—這些將項目的標識編碼在URL中(如上面的<id>)。

+ +

我們將使用路徑參數,來提取編碼信息,並將其傳遞給路由處理程序(在稍後的文章中,我們將使用它來動態確定從數據庫獲取的信息)。通過對我們的URL中的信息進行編碼,我們只需要一個路由,用於特定類型的每個資源(例如,一個路由來處理每個書本項目的顯示)。

+ +
+

注意 : Express允許您以任何方式構建URL -您可以在URL正文中編碼信息,就像上面一樣,或使用URL GET參數(例如/book/?id=6)。無論您使用哪種方法,URL都應保持乾淨,合理且可讀(請在此處查看W3C建議)。

+
+ +

接下來,我們為所有上述URL,創建路由處理程序回調函數和路由代碼。

+ +

創建路由-handler回調函式

+ +

在我們定義路由之前,我們將首先創建它們將調用的所有虛擬/骨架回調函數。回調將存在Books,BookInstances,Genres 和Authors 的單獨“控制器” 模塊中(您可以使用任何文件/模塊結構,但這似乎是該項目的適當粒度)。

+ +

首先在項目根目錄(/controllers)中,為我們的控制器創建一個文件夾,然後創建單獨的控制器文件/模塊,來處理每個模型:

+ +
/express-locallibrary-tutorial  //the project root
+  /controllers
+    authorController.js
+    bookController.js
+    bookinstanceController.js
+    genreController.js
+ +

作者控制器

+ +

打開/controllers/authorController.js文件,並複制以下代碼:

+ +
var Author = require('../models/author');
+
+// Display list of all Authors.
+exports.author_list = function(req, res) {
+    res.send('NOT IMPLEMENTED: Author list');
+};
+
+// Display detail page for a specific Author.
+exports.author_detail = function(req, res) {
+    res.send('NOT IMPLEMENTED: Author detail: ' + req.params.id);
+};
+
+// Display Author create form on GET.
+exports.author_create_get = function(req, res) {
+    res.send('NOT IMPLEMENTED: Author create GET');
+};
+
+// Handle Author create on POST.
+exports.author_create_post = function(req, res) {
+    res.send('NOT IMPLEMENTED: Author create POST');
+};
+
+// Display Author delete form on GET.
+exports.author_delete_get = function(req, res) {
+    res.send('NOT IMPLEMENTED: Author delete GET');
+};
+
+// Handle Author delete on POST.
+exports.author_delete_post = function(req, res) {
+    res.send('NOT IMPLEMENTED: Author delete POST');
+};
+
+// Display Author update form on GET.
+exports.author_update_get = function(req, res) {
+    res.send('NOT IMPLEMENTED: Author update GET');
+};
+
+// Handle Author update on POST.
+exports.author_update_post = function(req, res) {
+    res.send('NOT IMPLEMENTED: Author update POST');
+};
+
+ +

該模塊首先導入我們稍後將使用的模型,來訪問和更新我們的數據。然後它為我們希望處理的每個URL,導出函數(創建,更新和刪除操作使用表單,因此還有其他方法,來處理表單發布請求- 我們將在稍後的“表單文章” 中討論這些方法) 。

+ +

所有函數都具有Express中間件函數的標準形式,如果方法沒有完成請求週期,則會調用請求,響應和next下一個函數的參數(在所有這些情況下,它都會執行!)。這些方法只返回一個字符串,表明尚未創建關聯的頁面。如果期望控制器函數接收路徑參數,則在消息字符串中,輸出這些參數(參見上面的req.params.id)。

+ +

書本實例控制器

+ +

打開/controllers/bookinstanceController.js文件,並將其複製到以下代碼中(它遵循與Author控制器模塊相同的模式):

+ +
var BookInstance = require('../models/bookinstance');
+
+// Display list of all BookInstances.
+exports.bookinstance_list = function(req, res) {
+    res.send('NOT IMPLEMENTED: BookInstance list');
+};
+
+// Display detail page for a specific BookInstance.
+exports.bookinstance_detail = function(req, res) {
+    res.send('NOT IMPLEMENTED: BookInstance detail: ' + req.params.id);
+};
+
+// Display BookInstance create form on GET.
+exports.bookinstance_create_get = function(req, res) {
+    res.send('NOT IMPLEMENTED: BookInstance create GET');
+};
+
+// Handle BookInstance create on POST.
+exports.bookinstance_create_post = function(req, res) {
+    res.send('NOT IMPLEMENTED: BookInstance create POST');
+};
+
+// Display BookInstance delete form on GET.
+exports.bookinstance_delete_get = function(req, res) {
+    res.send('NOT IMPLEMENTED: BookInstance delete GET');
+};
+
+// Handle BookInstance delete on POST.
+exports.bookinstance_delete_post = function(req, res) {
+    res.send('NOT IMPLEMENTED: BookInstance delete POST');
+};
+
+// Display BookInstance update form on GET.
+exports.bookinstance_update_get = function(req, res) {
+    res.send('NOT IMPLEMENTED: BookInstance update GET');
+};
+
+// Handle bookinstance update on POST.
+exports.bookinstance_update_post = function(req, res) {
+    res.send('NOT IMPLEMENTED: BookInstance update POST');
+};
+
+ +

種類控制器

+ +

打開/controllers/genreController.js文件,並複制以下文本(這與AuthorBookInstance文件的模式相同):

+ +
var Genre = require('../models/genre');
+
+// Display list of all Genre.
+exports.genre_list = function(req, res) {
+    res.send('NOT IMPLEMENTED: Genre list');
+};
+
+// Display detail page for a specific Genre.
+exports.genre_detail = function(req, res) {
+    res.send('NOT IMPLEMENTED: Genre detail: ' + req.params.id);
+};
+
+// Display Genre create form on GET.
+exports.genre_create_get = function(req, res) {
+    res.send('NOT IMPLEMENTED: Genre create GET');
+};
+
+// Handle Genre create on POST.
+exports.genre_create_post = function(req, res) {
+    res.send('NOT IMPLEMENTED: Genre create POST');
+};
+
+// Display Genre delete form on GET.
+exports.genre_delete_get = function(req, res) {
+    res.send('NOT IMPLEMENTED: Genre delete GET');
+};
+
+// Handle Genre delete on POST.
+exports.genre_delete_post = function(req, res) {
+    res.send('NOT IMPLEMENTED: Genre delete POST');
+};
+
+// Display Genre update form on GET.
+exports.genre_update_get = function(req, res) {
+    res.send('NOT IMPLEMENTED: Genre update GET');
+};
+
+// Handle Genre update on POST.
+exports.genre_update_post = function(req, res) {
+    res.send('NOT IMPLEMENTED: Genre update POST');
+};
+
+ +

書本控制器

+ +

打開/controllers/bookController.js文件,並複制以下代碼。它遵循與其他控制器模塊相同的模式,但另外還有一個index()函數,用於顯示站點歡迎頁面:

+ +
var Book = require('../models/book');
+
+exports.index = function(req, res) {
+    res.send('NOT IMPLEMENTED: Site Home Page');
+};
+
+// Display list of all books.
+exports.book_list = function(req, res) {
+    res.send('NOT IMPLEMENTED: Book list');
+};
+
+// Display detail page for a specific book.
+exports.book_detail = function(req, res) {
+    res.send('NOT IMPLEMENTED: Book detail: ' + req.params.id);
+};
+
+// Display book create form on GET.
+exports.book_create_get = function(req, res) {
+    res.send('NOT IMPLEMENTED: Book create GET');
+};
+
+// Handle book create on POST.
+exports.book_create_post = function(req, res) {
+    res.send('NOT IMPLEMENTED: Book create POST');
+};
+
+// Display book delete form on GET.
+exports.book_delete_get = function(req, res) {
+    res.send('NOT IMPLEMENTED: Book delete GET');
+};
+
+// Handle book delete on POST.
+exports.book_delete_post = function(req, res) {
+    res.send('NOT IMPLEMENTED: Book delete POST');
+};
+
+// Display book update form on GET.
+exports.book_update_get = function(req, res) {
+    res.send('NOT IMPLEMENTED: Book update GET');
+};
+
+// Handle book update on POST.
+exports.book_update_post = function(req, res) {
+    res.send('NOT IMPLEMENTED: Book update POST');
+};
+
+ +

創建目錄路由模組

+ +

接下來,我們為LocalLibrary 網站,創建所需全部URL 的路由,這將調用我們在上一節中定義的控制器功能。

+ +

骨架網站已經有一個./routes文件夾,其中包含索引和用戶的路由。在此文件夾中,創建另一個路徑文件— catalog.js —如下圖所示。

+ +
/express-locallibrary-tutorial //the project root
+  /routes
+    index.js
+    users.js
+    catalog.js
+ +

打開/routes/ catalog.js,複製下面的代碼:

+ +
var express = require('express');
+var router = express.Router();
+
+// Require controller modules.
+var book_controller = require('../controllers/bookController');
+var author_controller = require('../controllers/authorController');
+var genre_controller = require('../controllers/genreController');
+var book_instance_controller = require('../controllers/bookinstanceController');
+
+/// BOOK ROUTES ///
+
+// GET catalog home page.
+router.get('/', book_controller.index);
+
+// GET request for creating a Book. NOTE This must come before routes that display Book (uses id).
+router.get('/book/create', book_controller.book_create_get);
+
+// POST request for creating Book.
+router.post('/book/create', book_controller.book_create_post);
+
+// GET request to delete Book.
+router.get('/book/:id/delete', book_controller.book_delete_get);
+
+// POST request to delete Book.
+router.post('/book/:id/delete', book_controller.book_delete_post);
+
+// GET request to update Book.
+router.get('/book/:id/update', book_controller.book_update_get);
+
+// POST request to update Book.
+router.post('/book/:id/update', book_controller.book_update_post);
+
+// GET request for one Book.
+router.get('/book/:id', book_controller.book_detail);
+
+// GET request for list of all Book items.
+router.get('/books', book_controller.book_list);
+
+/// AUTHOR ROUTES ///
+
+// GET request for creating Author. NOTE This must come before route for id (i.e. display author).
+router.get('/author/create', author_controller.author_create_get);
+
+// POST request for creating Author.
+router.post('/author/create', author_controller.author_create_post);
+
+// GET request to delete Author.
+router.get('/author/:id/delete', author_controller.author_delete_get);
+
+// POST request to delete Author.
+router.post('/author/:id/delete', author_controller.author_delete_post);
+
+// GET request to update Author.
+router.get('/author/:id/update', author_controller.author_update_get);
+
+// POST request to update Author.
+router.post('/author/:id/update', author_controller.author_update_post);
+
+// GET request for one Author.
+router.get('/author/:id', author_controller.author_detail);
+
+// GET request for list of all Authors.
+router.get('/authors', author_controller.author_list);
+
+/// GENRE ROUTES ///
+
+// GET request for creating a Genre. NOTE This must come before route that displays Genre (uses id).
+router.get('/genre/create', genre_controller.genre_create_get);
+
+//POST request for creating Genre.
+router.post('/genre/create', genre_controller.genre_create_post);
+
+// GET request to delete Genre.
+router.get('/genre/:id/delete', genre_controller.genre_delete_get);
+
+// POST request to delete Genre.
+router.post('/genre/:id/delete', genre_controller.genre_delete_post);
+
+// GET request to update Genre.
+router.get('/genre/:id/update', genre_controller.genre_update_get);
+
+// POST request to update Genre.
+router.post('/genre/:id/update', genre_controller.genre_update_post);
+
+// GET request for one Genre.
+router.get('/genre/:id', genre_controller.genre_detail);
+
+// GET request for list of all Genre.
+router.get('/genres', genre_controller.genre_list);
+
+/// BOOKINSTANCE ROUTES ///
+
+// GET request for creating a BookInstance. NOTE This must come before route that displays BookInstance (uses id).
+router.get('/bookinstance/create', book_instance_controller.bookinstance_create_get);
+
+// POST request for creating BookInstance.
+router.post('/bookinstance/create', book_instance_controller.bookinstance_create_post);
+
+// GET request to delete BookInstance.
+router.get('/bookinstance/:id/delete', book_instance_controller.bookinstance_delete_get);
+
+// POST request to delete BookInstance.
+router.post('/bookinstance/:id/delete', book_instance_controller.bookinstance_delete_post);
+
+// GET request to update BookInstance.
+router.get('/bookinstance/:id/update', book_instance_controller.bookinstance_update_get);
+
+// POST request to update BookInstance.
+router.post('/bookinstance/:id/update', book_instance_controller.bookinstance_update_post);
+
+// GET request for one BookInstance.
+router.get('/bookinstance/:id', book_instance_controller.bookinstance_detail);
+
+// GET request for list of all BookInstance.
+router.get('/bookinstances', book_instance_controller.bookinstance_list);
+
+module.exports = router;
+
+ +

該模塊導入Express,然後使用它來創建一個Router對象。路由都在路由器上設置完成,然後導出。

+ +

路由是使用路由器對像上的.get().post()方法定義的。所有路徑都是使用字符串定義的(我們不使用字符串模式或正則表達式)。作用於某些特定資源(如書籍)的路由,則使用路徑參數從URL中獲取對象標識id。

+ +

處理程序函數,都是從我們在上一節中,創建的控制器模塊導入的。

+ +

更新 index 路由模組

+ +

我們已經設置了所有新路由,但我們仍然有一個到原始頁面的路由。讓我們將其重定向,到我們在路徑'/ catalog' 創建的新索引頁面。

+ +

打開/routes/index.js並使用下面的函數,替換現有路由。

+ +
// GET home page.
+router.get('/', function(req, res) {
+  res.redirect('/catalog');
+});
+ +
+

注意:這是我們第一次使用redirect()響應方法。這會重定向到指定的頁面,默認情況下會發送HTTP狀態代碼“302 Found”。您可以根據需要,更改返回的狀態代碼,並提供絕對路徑或相對路徑。

+
+ +

更新app.js

+ +

最後一步,是將路由,添加到中間件鏈。我們在app.js這樣做。

+ +

打開app.js,並要求其他路由下方的目錄路由(添加下面顯示的第三行,在其他兩個路由下面):

+ +
var indexRouter = require('./routes/index');
+var usersRouter = require('./routes/users');
+var catalogRouter = require('./routes/catalog');  //Import routes for "catalog" area of site
+ +

接下來,將目錄路由,添加到其他路由下面的中間件堆棧(添加下面顯示的第三行,在其他兩行下面):

+ +
app.use('/', indexRouter);
+app.use('/users', usersRouter);
+app.use('/catalog', catalogRouter);  // Add catalog routes to middleware chain.
+ +
+

Note:   我們已在路徑'/catalog'中添加了目錄模塊。它預先添加到目錄模塊中定義的所有路徑。例如,要訪問書本列表,URL將為:/catalog/books/

+
+ +

就是這樣。現在應該為我們最終在LocalLibrary 網站上支持的所有URL,啟用路由和框架功能。

+ +

測試路由

+ +

要測試路由,首先使用您通常的方法啟動網站

+ + + +

然後瀏覽一些上面的LocalLibrary URL,並驗證您沒有收到錯誤頁面(HTTP 404)。為方便起見,下面列出了一小組網址:

+ + + +

總結

+ +

我們現在為網站創建了所有的路由,在稍後的教程,我們可以將實作完成的代碼,填入到空殼控制器函式。以這樣的方式,我們學到了許多關於Express 路由的基本信息,以及一些組織路由和控制器的方式。

+ +

下一篇文章,我們將使用視圖(模板) 和存在模型裡的信息,為網站創建一個合適的歡迎頁面。

+ +

參閱

+ + + +

{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/mongoose", "Learn/Server-side/Express_Nodejs/Displaying_data", "Learn/Server-side/Express_Nodejs")}}

+ +

 

+ +

本教程連結

+ + + +

 

diff --git a/files/zh-tw/learn/server-side/express_nodejs/skeleton_website/index.html b/files/zh-tw/learn/server-side/express_nodejs/skeleton_website/index.html new file mode 100644 index 0000000000..0139a30dd9 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/skeleton_website/index.html @@ -0,0 +1,506 @@ +--- +title: 'Express 教學 2: 創建一個骨架網站' +slug: Learn/Server-side/Express_Nodejs/skeleton_website +translation_of: Learn/Server-side/Express_Nodejs/skeleton_website +--- +
{{LearnSidebar}}
+ +

{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs/mongoose", "Learn/Server-side/Express_Nodejs")}}

+ +

Express 教程的第二篇文章,演示如何創建一個 "骨架" 網站項目,你可以接著在裡面加入網站特定的路由、模板/視圖、和數据庫調用。

+ + + + + + + + + + + + +
前置條件:架設一個Node 開發環境。回顧Express 教程。
目標:能夠使用Express 應用產生器,創建自己新的網頁項目。
+ +

概覽

+ +

本文演示如何使用 Express 應用產生器 工具,創建一個 "骨架" 網站,然後您可以使用特定於站點的路由,視圖/模板和數據庫調用來填充它們。在這個教程,我們將使用該工具,為我們的本地圖書館網站創建框架,我們稍後將添加該網站所需的所有其他代碼。該過程非常簡單,只需要在命令行上,用新項目名稱調用生成器,還可以指定站點的模板引擎和 CSS 生成器。

+ +

以下部分向您展示如何調用應用程序生成器,並提供關於視圖或CSS的不同選項的一些解釋。我們還將解釋骨架網站的結構。最後,我們將展示如何運行網站,來驗證它是否有效。

+ +
+

注意: Express Application Generator並非 Express 應用程序的唯一生成器,生成的項目不是構建文件和目錄的唯一可行方式。然而,生成的網站具有易於擴展和理解的模塊化結構。有關最小 Express 應用程序的信息,請參閱 Hello world 示例(Express docs)。

+
+ +

使用應用產生器

+ +

您應該已經安裝了生成器,作為設置 Node 開發環境的一部分。作為快速提醒,您可以使用 NPM 軟件包管理器,在整個站點安裝生成器工具,如下所示:

+ +
npm install express-generator -g
+ +

生成器有許多選項,您可以使用--help(或-h)命令,在命令行上查看它們:

+ +
> express --help
+
+  Usage: express [options] [dir]
+
+  Options:
+
+    -h, --help           output usage information
+        --version        output the version number
+    -e, --ejs            add ejs engine support
+        --pug            add pug engine support
+        --hbs            add handlebars engine support
+    -H, --hogan          add hogan.js engine support
+    -v, --view <engine>  add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)
+    -c, --css <engine>   add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
+        --git            add .gitignore
+    -f, --force          force on non-empty directory
+
+ +

您可以使用 Jade 視圖引擎和純 CSS 來指定 express,以在當前目錄中創建項目(如果指定目錄名,則項目將創建在具有該名稱的子文件夾中)。

+ +
express
+ +

您還可以使用--view選擇視圖(模板)引擎,並且/或者使用--css選擇 CSS 生成引擎。

+ +
+

注意: 選擇模板引擎的其他選項(例如 --hogan, --ejs, --hbs等)已被棄用。請用 --view (或 -v)!

+
+ +

我應該用哪個視圖引擎?

+ +

Express Application Generator 允許您配置許多流行的視圖/模板引擎,包括 EJS, Hbs, Pug (Jade), Twig, 和 Vash,但如果您沒有指定視圖選項,它會默認選擇Jade。 Express 本身也可以支持大量其他模板語言,是「開箱即可使用」的。

+ +
+

注意: 如果要使用生成器不支持的模板引擎,請參閱在Express中使用模板引擎(Express文檔),並參閱目標視圖引擎的文檔。

+
+ +

一般來說,您應該選擇一種「可以提供您所需的所有功能」的模板引擎,
+ 並使您能夠儘早提高生產力 - 換句話說,就像您選擇其他組件一樣!比較模板引擎時需要考慮的一些事項如下:

+ + + +
+

提示: 互聯網上有許多資源,可幫助您比較不同的視圖/模板引擎選擇!

+
+ +

對於這個項目,我們將使用 Pug 模板引擎(這是最近更名的 Jade 引擎),因為這是最流行的 Express / JavaScript 模板語言之一,並且應用發生器支持開箱即用。

+ +

我應該用哪個CSS樣式引擎?

+ +

Express 應用生成器允許您創建一個項目,並配置最常見的 CSS 樣式表引擎:LESS, SASS, Compass, Stylus

+ +
+

注意: CSS有一些限制,使某些任務變得困難。 CSS 樣式表引擎允許您使用更強大的語法來定義您的 CSS,然後將定義編譯為純粹的舊式 CSS,以供瀏覽器使用。

+
+ +

與模板引擎一樣,您應該使用樣式表引擎,這樣可以讓您的團隊獲得最高生產力。對於這個項目,我們將使用普通的 CSS(默認值),因為我們的 CSS 要求不夠複雜,沒有必要使用其他任何東西。

+ +

我應該用哪個數據庫?

+ +

生成的代碼不使用/包含任何數據庫。 Express 應用程序可以使用 Node支持的任何數據庫機制(Express 本身並未針對數據庫管理,定義任何特定的附加行為/要求)。
+ 我們將在後面的文章中,討論如何與數據庫集成。

+ +

創建項目

+ +

對於我們要構建的示例 Local Library 應用程序,我們將使用 Pug 模板庫,創建一個名為 express-locallibrary-tutorial 的項目,並且不使用 CSS樣式表引擎。

+ +

首先到要創建項目的位置,然後在命令提示符下,運行 Express 應用生成器,如下所示:

+ +
express express-locallibrary-tutorial --view=pug
+
+ +

成器將創建(並列出)項目的文件。

+ +
   create : express-locallibrary-tutorial
+   create : express-locallibrary-tutorial/package.json
+   create : express-locallibrary-tutorial/app.js
+   create : express-locallibrary-tutorial/public/images
+   create : express-locallibrary-tutorial/public
+   create : express-locallibrary-tutorial/public/stylesheets
+   create : express-locallibrary-tutorial/public/stylesheets/style.css
+   create : express-locallibrary-tutorial/public/javascripts
+   create : express-locallibrary-tutorial/routes
+   create : express-locallibrary-tutorial/routes/index.js
+   create : express-locallibrary-tutorial/routes/users.js
+   create : express-locallibrary-tutorial/views
+   create : express-locallibrary-tutorial/views/index.pug
+   create : express-locallibrary-tutorial/views/layout.pug
+   create : express-locallibrary-tutorial/views/error.pug
+   create : express-locallibrary-tutorial/bin
+   create : express-locallibrary-tutorial/bin/www
+
+   install dependencies:
+     > cd express-locallibrary-tutorial && npm install
+
+   run the app:
+     > SET DEBUG=express-locallibrary-tutorial:* & npm start
+ +

在輸出結束時,生成器提供關於「如何安裝依賴關係」的指示信息(如 package.json 文件中所列),以及如何運行應用程序(上述說明適用於 Windows;在 Linux / macOS上,它們會略有不同)。

+ +

運行骨架網站

+ +

在這一時間點上,我們有一個完整的骨架項目。該網站實際上並沒有做太多工作,但運行它,能夠展示它是如何工作的。

+ +
    +
  1. 首先安裝依賴項(install安裝命令,將獲取項目的 package.json 文件中列出的所有依賴項包)。 + +
    cd express-locallibrary-tutorial
    +npm install
    +
  2. +
  3. 然後運行該應用程序。 +
      +
    • 在Windows上,使用此命令: +
      SET DEBUG=express-locallibrary-tutorial:* & npm start
      +
    • +
    • 在macOS 或 Linux,使用此命令: +
      DEBUG=express-locallibrary-tutorial:* npm start
      +
      +
    • +
    +
  4. +
  5. 然後在瀏覽器中加載 http://localhost:3000/ ,以訪問該應用程序。
  6. +
+ +

你應該會看到一個瀏覽器頁面,就像這樣:

+ +

Browser for default Express app generator website

+ +

你有一個能工作的 Express 應用了,讓它在 http://localhost:3000/ 服務。

+ +
+

注意: 您也可以使用 npm start命令啟動應用程序。如下圖所示,指定 DEBUG 變量可啟用控制台日誌記錄/調試。例如,當你訪問上面的頁面時,你會看到像這樣的調試輸出:

+ +
>SET DEBUG=express-locallibrary-tutorial:* & npm start
+
+> express-locallibrary-tutorial@0.0.0 start D:\express-locallibrary-tutorial
+> node ./bin/www
+
+  express-locallibrary-tutorial:server Listening on port 3000 +0ms
+GET / 200 288.474 ms - 170
+GET /stylesheets/style.css 200 5.799 ms - 111
+GET /favicon.ico 404 34.134 ms - 1335
+
+ +

讓伺服器在檔案更改時重新啟動

+ +

在您重新啟動服務器之前,您對 Express 網站所做的任何更改,目前都不可見。每次進行更改時,必須停止並重新啟動服務器,很快變得非常煩人,因此值得花時間使服務器在需要時,自動重新啟動。

+ +

這種工具中,最簡單的之一就是 nodemon。這通常是全局安裝的(因為它是一個“工具”),但在這裡,我們將在本地安裝和使用它,作為開發人員依賴項,以便任何使用該項目的開發人員,在安裝應用程序時自動獲取它。在骨架項目的根目錄中,使用以下命令:

+ +
npm install --save-dev nodemon
+ +

如果您打開項目的 package.json 文件,您現在將看到一個具有此依賴關係的新區段:

+ +
  "devDependencies": {
+    "nodemon": "^1.14.11"
+  }
+
+ +

由於該工具沒有全局安裝,我們無法從命令行啟動它(除非我們將其添加到路徑中),但是我們可以從 NPM 腳本中調用它,因為 NPM 知道所有關於安裝的軟件包的信息。找到你的 package.json 的腳本 scripts 區塊。我們更新 scripts 區塊,最初的一行,以"start"開頭,在該行的末尾添加逗號,並添加 "devstart" 開頭的一行,如下所示:

+ +
  "scripts": {
+    "start": "node ./bin/www",
+    "devstart": "nodemon ./bin/www"
+  },
+
+ + + +

現在我們可以用與前面幾乎完全相同的方式,啟動服務器,但使用指定的 devstart 命令:

+ + + +
+

注意: 現在,如果您編輯項目中的任何文件,服務器將重新啟動(或者您可以隨時在命令提示符下,鍵入rs來重新啟動它)。您仍需要重新加載瀏覽器,以刷新頁面。

+ +

我們現在必須調用“npm run <scriptname>”而不是 npm start,因為“start”實際上是映射到指定腳本的 NPM 命令。我們可以在啟動腳本中替換該命令,但我們只想在開發期間使用 nodemon,因此創建新的腳本命令是有意義的。

+
+ +

從產生器得到的項目

+ +

現在我們來看看我們剛剛創建的項目。

+ +

目錄結構

+ +

從產生器得到的生成項目,現在已經安裝了依賴項,具有以下文件結構 (不帶前綴 “/” 的項目,表示文件)。 package.json 文件定義了應用程序依賴項,和其他信息。它還定義了一個啟動腳本,它將調用應用程序入口點 JavaScript 文件 /bin/www。這設置了一些應用程序的錯誤處理,然後加載 app.js ,來完成剩下的工作。應用程序路徑,存儲在 /routes 目錄下的單獨模塊中。模板存儲在 /views 目錄下。

+ +
/express-locallibrary-tutorial
+    app.js
+    /bin
+        www
+    package.json
+    /node_modules
+        [about 4,500 subdirectories and files]
+    /public
+        /images
+        /javascripts
+        /stylesheets
+            style.css
+    /routes
+        index.jsusers.js
+    /views
+        error.pug
+        index.puglayout.pug
+
+
+ +

以下各節將詳細介紹這些文件。

+ +

package.json

+ +

package.json 文件定義了應用程序依賴關係,和其他訊息:

+ +
{
+  "name": "express-locallibrary-tutorial",
+  "version": "0.0.0",
+  "private": true,
+  "scripts": {
+    "start": "node ./bin/www",
+    "devstart": "nodemon ./bin/www"
+  },
+  "dependencies": {
+    "body-parser": "~1.18.2",
+    "cookie-parser": "~1.4.3",
+    "debug": "~2.6.9",
+    "express": "~4.16.2",
+    "morgan": "~1.9.0",
+    "pug": "~2.0.0-rc.4",
+    "serve-favicon": "~2.4.5"
+  },
+  "devDependencies": {
+    "nodemon": "^1.14.11"
+  }
+}
+
+ +

依賴關係包括 express 套件,和我們所選視圖引擎(pug)的套件。另外,我們還有以下的套件,在許多 Web 應用程序中很有用:

+ + + +

腳本部分,定義了一個“開始” "start" 腳本,當我們調用 npm start 來啟動服務器時,這就是我們所調用的腳本。從腳本定義中,您可以看到這實際上用 node 啟動了 JavaScript 文件 ./bin/www。它還定義了一個“devstart” 腳本,我們在調用 npm run devstart 時調用它。這將啟動相同的 ./bin/www 文件,但使用 nodemon 調用而不是 node 。

+ +
  "scripts": {
+    "start": "node ./bin/www",
+    "devstart": "nodemon ./bin/www"
+  },
+
+ +

www 文件

+ +

文件 /bin/www 是應用程序入口點!它做的第一件事是 require() “真正的” 應用程序入口點(即項目根目錄中的 app.js ),app.js 會設置並返回 express()應用程序的對象。

+ +
#!/usr/bin/env node
+
+/**
+ * Module dependencies.
+ */
+
+var app = require('../app');
+
+ +
+

注意: require() 是一個全局 node 函數,用於將模塊導入當前文件。這裡我們使用相對路徑指定 app.js 模塊,並省略可選的(.js)文件擴展名。

+
+ +

此文件中的其餘代碼,將設置一個node 運行的HTTP 服務器,並將應用app 設置為特定的端口(在環境變量中定義,如果變量未定義,則定義為3000),並開始監聽和報告服務器錯誤和連接。現在你並不需要知道代碼的其他內容(這個文件中的所有內容都是 “樣板文件” ),但如果你感興趣,可以隨時查看它。

+ +

app.js

+ +

此文件創建一個 express 應用程序對象(按傳統命名為 app),使用各種設置和中間件,以設置應用程序,然後從模塊導出應用程序。下面的代碼只顯示了文件的一部分,創建和導出應用程序對象的部分:

+ +
var express = require('express');
+var app = express();
+...
+module.exports = app;
+
+ +

回到上面的 www 入口點文件,它是在導入該文件時,提供給調用者的這個 module.exports 對象。

+ +

讓我們詳細了解 app.js 文件。首先,我們使用 require()將一些有用的 node 庫導入到文件中,其中包括我們先前使用 NPM 為應用程序下載的 express,serve-favicon,morgan,cookie-parser 和body-parser;和path 庫,它是解析文件和目錄路徑的核心 node 庫。

+ +
var express = require('express');
+var path = require('path');
+var favicon = require('serve-favicon');
+var logger = require('morgan');
+var cookieParser = require('cookie-parser');
+var bodyParser = require('body-parser');
+
+ +

然後我們用 require()導入來自我們的路由目錄的模塊。這些模塊/文件包含用於處理特定的相關“路由”集合(URL路徑)的代碼。當我們擴展骨架應用程序,例如列出圖書館中的所有書籍時,我們將添加一個新文件,來處理與書籍相關的路由。

+ +
var indexRouter = require('./routes/index');
+var usersRouter = require('./routes/users');
+
+ +
+

注意: 此時我們剛剛導入了模塊;我們還沒有真正使用過它的路由(在文件的更下方一點將使用到路由)。

+
+ +

接下來,我們使用導入的 express 模塊​​,創建應用程序 app 對象,然後使用它來設置視圖(模板)引擎。引擎的設置有兩個部分。首先我們設置 'views' 值,來指定模板將被存儲的文件夾(在這種情況下是子文件夾 /views)。然後我們設置 'view engine' 的值,來指定模板庫(在本例中為 “pug” )。

+ +
var app = express();
+
+// view engine setup
+app.set('views', path.join(__dirname, 'views'));
+app.set('view engine', 'pug');
+
+ +

下一組函數調用 app.use(),將中間件的庫,添加到請求處理鏈中。除了我們之前導入的第三方庫之外,我們還使用 express.static 中間件,來使 Express 提供在項目根目錄下,/public 目錄中的所有靜態文件。

+ +
// uncomment after placing your favicon in /public
+//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
+app.use(logger('dev'));
+app.use(bodyParser.json());
+app.use(bodyParser.urlencoded({ extended: false }));
+app.use(cookieParser());
+app.use(express.static(path.join(__dirname, 'public')));
+
+ +

現在所有其他中間件都已設置完畢,我們將(先前導入的)路由處理代碼,添加到請求處理鏈中。導入的代碼,將為網站的不同部分定義特定路由:

+ +
app.use('/', indexRouter);
+app.use('/users', usersRouter);
+
+ +
+

注意: 上面指定的路徑 ('/' and '/users'),被視為定義在導入文件中的路由前綴。因此,例如,如果導入的用戶模塊 users/profile定義了路由,則可以在 /users/profile中訪問該路由。我們將在後面的文章中,詳細討論路由。

+
+ +

文件中的最後一個中間件,為錯誤和 HTTP 404 響應添加了處理程序方法。

+ +
// catch 404 and forward to error handler
+app.use(function(req, res, next) {
+  var err = new Error('Not Found');
+  err.status = 404;
+  next(err);
+});
+
+// error handler
+app.use(function(err, req, res, next) {
+  // set locals, only providing error in development
+  res.locals.message = err.message;
+  res.locals.error = req.app.get('env') === 'development' ? err : {};
+
+  // render the error page
+  res.status(err.status || 500);
+  res.render('error');
+});
+
+ +

Express 應用程序對象(app)現已完全完成配置。最後一步,是將其添加到模塊導出(這允許它通過 /bin/www 導入)。

+ +
module.exports = app;
+ +

路由

+ +

路由文檔 /routes/users.js 如下所示(路由文件共享一個類似的結構,所以我們不需要也顯示 index.js)。首先加載 express 模塊​​,並使用它獲取 express.Router對象。然後它在該對像上指定一個路由,最後從模塊中導出路由器(這就是允許將文件導入到 app.js 中的路由)。

+ +
var express = require('express');
+var router = express.Router();
+
+/* GET users listing. */
+router.get('/', function(req, res, next) {
+  res.send('respond with a resource');
+});
+
+module.exports = router;
+
+ +

該路由定義了一個回調,只要檢測到具有正確模式的HTTP GET 請求,就會調用該回調。匹配模式是模塊導入時指定的路由('/users'),加上('/')文件中定義的任何內容。換句話說,當收到/users/的 URL 時,將使用此路由。

+ +
+

提示: 嘗試運行帶有 node 的服務器,並在瀏覽器中訪問以下 URL: http://localhost:3000/users/。您應該看到一條消息:'respond with a resource'。

+
+ +

上面有趣的事情是,回調函數有第三個參數 'next',因此是一個中間件函數,而不是簡單的路由回調。雖然代碼當前不使用 next 參數,但如果要在'/'根路由路徑中,添加多個路由處理程序,將來可能會有用。

+ +

視圖(模板)

+ +

視圖(模板)存儲在 /views 目錄中(如 app.js 中指定的)並且被賦予文件擴展名.pug。方法 Response.render()用於呈現指定的模板,以及在對像中傳遞的命名變量的值,然後將結果作為響應發送。在來自 /routes/index.js 的以下代碼中,您可以看到,該路由如何使用模板 "index" 傳遞模板變量 "title" ,以呈現響應。

+ +
/* GET home page. */
+router.get('/', function(req, res) {
+  res.render('index', { title: 'Express' });
+});
+
+ +

上面路由的相應模板在下面給出(index.pug)。我們稍後會詳細討論這個語法。您現在需要知道的是,標題變量 title(值為 'Express')將插入模板中指定的位置。

+ +
extends layout
+
+block content
+  h1= title
+  p Welcome to #{title}
+
+ +

挑戰自己

+ +

/routes/users.js 中創建一個新路由,它將在 /users/cool/上顯示文本 “You're so cool”。通過運行服務器,並在瀏覽器中訪問 http://localhost:3000/users/cool/ 來測試它。

+ + + +

總結

+ +

你現在為 本地圖書館 創建了一個骨架網站項目,並且用 node 驗證了它能夠運行。最重要的,你也理解了項目的結構,因此你也明白了我們需要為本地圖書館加上路由和視圖。

+ +

接下來我們將開始修改骨架,讓它能像一個圖書館網站一樣運作。

+ +

參閱

+ + + +

{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs/mongoose", "Learn/Server-side/Express_Nodejs")}}

+ + + +

本教程連結

+ + diff --git a/files/zh-tw/learn/server-side/express_nodejs/tutorial_local_library_website/index.html b/files/zh-tw/learn/server-side/express_nodejs/tutorial_local_library_website/index.html new file mode 100644 index 0000000000..6804ef3742 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/tutorial_local_library_website/index.html @@ -0,0 +1,91 @@ +--- +title: 'Express 教學 1: 本地圖書館網站' +slug: Learn/Server-side/Express_Nodejs/Tutorial_local_library_website +translation_of: Learn/Server-side/Express_Nodejs/Tutorial_local_library_website +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/development_environment", "Learn/Server-side/Express_Nodejs/skeleton_website", "Learn/Server-side/Express_Nodejs")}}
+ +

我們實作教程系列的第一篇文章,會說明將學到什麼東西,並提供「本地圖書館」範例網站的概述 。我們將在接下來的文章中一步一步完成這個網站。

+ + + + + + + + + + + + +
前置條件:閱讀 Express 介紹。 在底下的教程,你將需要 架設一個 Node 開發環境。
目標:介紹本教程的範例應用,讓讀者理解包含哪些主題。
+ +

概覽

+ +

歡迎來到 MDN "本地圖書館" Express (Node) 教程,我們將開發一個網站,用於管理本地圖書館的目錄。

+ +

本系列教程文章中,你將會:

+ + + +

這些主題中,有一部分你可能已經學過了,或者曾經簡短的接觸過。在本列系教程的最後,你應該知道的夠多,能夠自己開發簡單的 Express 應用。

+ +

本地圖書館網站

+ +

我們接下來將創建,並隨著本系列教程發展的網站,名字是本地圖書館。如同你的預測,此網站的目的,是為一間小型本地圖書館,提供一個線上目錄,使用者能夠瀏覽可取得的書本,並管理他們的帳号。

+ +

本範例經過細心地考慮,因為它的規模可以放大或縮小,以配合我們的需要,演示盡可能多或少的細節。並且可以用來演示幾乎所有的 Express 特性。更重要的,它允許我們提供一條引導路徑,演示你在任何網站都會需要的功能:

+ + + +

即使這是一個具備相當擴充性的範例,它被叫做本地圖書館是有原因的 — 我們希望呈現給你最少的信息,能夠盡快幫助你上手並運行Express。因此,我們將會存放書本、複本、作者、和其它關鍵信息。然而,我們不會存放其它圖書館可能用到的有關信息,或者提供支持多個圖書館網站的架構,又或者其它 "大型圖書館" 的特性。

+ +

我被卡住了,哪裡可以得到原始碼?

+ +

當你使用本教程,我們將在每個知識點,提供適當的代碼片段,讓你複制貼上,同時有些代碼,我們希望你能自己擴充 (會有一些指引)。

+ +

如果你被卡住了,你可以在 Github 的這裡,找到本地圖書館網站已經開發完成的版本。

+ +
+

注意: 在本教程中,指定版本的 node、Express、還有其它模組,都經過測試,並列出在專案項目的 package.json 檔案中。

+
+ +

總結Edit

+ +

現在,你對本地圖書館網站以及將要學習的東西,有更多一點的認識,是時候開始創建一個 骨架項目,以存放我們的範例。

+ +

 

+ +

{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/development_environment", "Learn/Server-side/Express_Nodejs/skeleton_website", "Learn/Server-side/Express_Nodejs")}}

+ +

 

+ +

 

+ +

本系列教學

+ + + +

 

diff --git a/files/zh-tw/learn/server-side/first_steps/index.html b/files/zh-tw/learn/server-side/first_steps/index.html new file mode 100644 index 0000000000..2afd7bb1d4 --- /dev/null +++ b/files/zh-tw/learn/server-side/first_steps/index.html @@ -0,0 +1,41 @@ +--- +title: 伺服器端程式設計起步走 +slug: Learn/Server-side/First_steps +translation_of: Learn/Server-side/First_steps +--- +
{{LearnSidebar}}
+ +

在我們的伺服器端程式設計模組內,我們會回答一些關於伺服器端編程的問題──「那是什麼?」、「它和用戶端程式設計有何不同?」、還有「為什麼它有用?」。接著,我們會比較各大熱門框架、並佐以一些如何選擇最適合框架的指引。最後,我們還會提供關於伺服器安全的進階介紹性文章。

+ +

(譯者 iigmir 註:你可能常常聽到網路開發有前端與後端。在網路開發的脈落下,這裡講的伺服器端程式設計,就是俗稱的後端。)

+ +

先決條件

+ +

在開始本模組前,你不需要擁有任何與伺服器端、或其他種類的程式設計相關知識。

+ +

你必須知道「網路如何運作」。關於此,我們推薦以下主題:

+ + + +

有了基本理解後,你就可以透過本章節的模組來完成工作。

+ +

指引

+ +
+
介紹伺服器端
+
歡迎來到 MDN 初學者的伺服器端程式設計課程!在這首篇文章中,我們將以很高的角度回答諸如「這是什麼?」、「它和用戶端程式設計有何不同?」、還有「為什麼它有用?」之類的問題。讀完以後,你會明白很多關於伺服器端程式設計的知識。
+
用戶端概覽
+
現在你知道了伺服器端程式設計的目標與益處,而我們現在要檢驗一些細節:當伺服器從瀏覽器那邊收到「動態請求」的時候,究竟發生了什麼事。因為大多數網站都用相近的方法處理請求與回應,所以這一點會幫助你理解自己在撰寫程式碼的時候要幹什麼。
+
伺服器端網路框架
+
最後一篇文章介紹了伺服器端網路程式,為了回應來自瀏覽器的請求,究竟需要些什麼。現在,我們會告訴你網路框架如何簡化那些工作,並幫助你選定自己的第一個網路程式,要用上什麼樣的框架。
+
網站安全
+
網站安全,有賴網頁設計時的高度警覺。這篇概要性的文章不是要讓你變成網站安全大神,而是幫你理解在強化網路程式免受大多數威脅時,第一要務為何。
+
+ +

評估

+ +

這份「概覽」模組不做任何評估,因為我們還沒有給你看過任何程式碼。我們希望到了這裡,你可以對伺服器端程式設計能提供什麼東西,有者良好的理解;我們也希望你能在建立第一個網站時要用什麼框架的方面,能夠下好決定。

diff --git "a/files/zh-tw/learn/server-side/first_steps/\344\273\213\347\264\271/index.html" "b/files/zh-tw/learn/server-side/first_steps/\344\273\213\347\264\271/index.html" new file mode 100644 index 0000000000..a0919697ee --- /dev/null +++ "b/files/zh-tw/learn/server-side/first_steps/\344\273\213\347\264\271/index.html" @@ -0,0 +1,225 @@ +--- +title: 伺服器端的介紹 +slug: Learn/Server-side/First_steps/介紹 +translation_of: Learn/Server-side/First_steps/Introduction +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/Server-side/First_steps/Client-Server_overview", "Learn/Server-side/First_steps")}}
+ +

歡迎來到MDN伺服器端程式設計的初學者課程 !在第一篇文章中,我們會用較為抽象的角度來探討 server-side programming,並且為你解答「這是什麼?」「這個和用戶端的程式有什麼不同?」以及「這個有什麼用?」 。在讀完這篇文章後,你將能明白如何透過 server-side coding 來為你的網站增添力量。

+ + + + + + + + + + + + +
先決條件:基本電腦知識、對網路伺服器有基本了解。
目標:認識伺服器端的程式設計、它可以做什麼、它和用戶端的程式有什麼不一樣?
+ +

大多數的大型網站使用伺服器端程式(server-side code)來動態地顯示各種所需的資料,普遍的做法為從伺服端的資料庫中取出資料,並送至用戶端,再透過一些 code 來顯示它們(例如:HTML 與 JavaScript)。

+ +

也許,使用伺服器端程式的最大好處是為不同的瀏覽者量身打造網頁內容。動態網站根據使用者的偏好設定及興趣提供更為相關的內容,也可以儲存個人設定及資訊讓網站更易於使用 — 例如重複使用已儲存的信用卡資料來使付款流程更為順暢。

+ +

它也能讓網站透過信件或其他方式來和使用者互動,如發送通知與更新。這一切的一切都讓網站更能牢牢抓住使用者的心。

+ +

何謂伺服器端網站程式開發?

+ +

網頁瀏覽器使用超文本傳輸協定(HyperText Transfer Protocol, {{glossary("HTTP")}})與網頁伺服器(web servers)溝通。當您點選網頁上的連結、送出表單,或者執行搜尋,一段 HTTP 請求request)會由您的瀏覽器送至目標伺服器。

+ +

該請求(request)包含一個用來指定受影響資源的 URL、一個定義行為的請求方法(例如對資源進行get、delete或post)與當進行HTTP POST方法時可能包含編碼於URL參數中的額外資訊(經由一段查詢字串送出的各個鍵值對),或是在關聯的{{glossary("Cookie", "cookies")}}中。

+ +

網頁伺服器等待用戶端的請求訊息、獲得後處理它們,並以一個HTTP回應response)訊息回覆至網頁瀏覽器。該回應包含一個狀態訊息說明本次請求是否達成(例如:"HTTP/1.1 200 OK"表示成功)。

+ +

成功對應於一個請求的回應主體(response body)應包含請求的資源(例如:一份新的HTML頁面或一張圖片等),這些可能將被用來顯示在網頁瀏覽器中。

+ +

靜態網站

+ +

以下的靜態網站(static site)圖展示一個基本的網頁伺服器架構,其中靜態網站意謂當無論何時有個特定資源的請求,伺服器始終回傳相同的硬編碼內容(hard-coded content)。當一個使用者想要引導到一個網頁時,瀏覽器送出的HTTP "GET" 請求指的就是該資源的URL。

+ +

此伺服器從它的檔案系統取回被請求的文件,並回傳一個包含此文件以及成功狀態碼(通常為200 OK)的HTTP回應。若檔案因某些原因無法被取回,則回傳一個錯誤狀態(參見 用戶端錯誤回應 與 伺服器端錯誤回應)。

+ +

A simplified diagram of a static web server.

+ +

動態網站

+ +

一個動態網站的回應內容是當需要時動態產生的。在一個動態網站的HTML網頁通常是經由資料庫取得並插入資料至HTML範本的佔位符(placeholders)中而創造出來(相較於靜態網站,這對於儲存大量內容而言,這是一種相當有效率的做法)。 

+ +

一個動態網站可以根據使用者或已存偏好設定提供的URL資訊回傳不同的資料,也可以以其他的作用方式呈現回應(例如:發送通知)。

+ +

用來支援一個動態網站的大部分的程式碼必須在伺服器執行。建立程式碼的方式稱為"伺服端程式設計(server-side programming)"或"後端腳本(back-end scripting)"。

+ +

下圖為動態網站dynamic website)的基本架構。如同先前的圖說,瀏覽器發送HTTP請求至伺服器,接著伺服器處理請求後,回傳合適的HTTP回應。

+ +

對於靜態資源的請求處理方式如同靜態網站的方式(靜態資源為任何不會改變的檔案 — 通常為CSS、JavaScript、圖片、預產生的PDF檔案等)。 

+ +

A simplified diagram of a web server that uses server-side programming to get information from a database and construct HTML from templates. This is the same diagram as is in the Client-Server overview.

+ +

對於動態資源的請求方式則為轉送(2)至伺服端程式碼(如圖中的網頁應用程式 Web Application)。對於"動態請求",伺服器解釋該請求、從資料庫讀取所需資訊(3)、與HTML範本結合取得的資料(4),最後送回一個包含已產生HTML的回應(5,6)。

+ +
+

伺服端與用戶端程式設計是相同的嗎?

+
+ +

讓我們把注意力集中在伺服端與用戶端的程式設計吧!在以下的每個案例中,程式碼完全不一樣:

+ + + +

執行在瀏覽器的程式碼被稱為用戶端程式碼client-side code),它主要用來改善一個渲染的網頁外觀與行為。這包含選取與設定UI元件樣式、建立佈局、導覽、表格驗證等。相對的,伺服端網站程式設計大量涉及要回傳哪些內容給瀏覽器做為對請求的回應。伺服端程式碼處理驗證已提交的資料與請求、使用資料庫儲存及取得資料,和按需求發送正確的資料給用戶等任務。

+ +

用戶端程式碼以HTMLCSSJavaScript撰寫 — 它執行在網頁瀏覽器內,並且僅有或無訪問底層的作業系統(包含對檔案系統的有限存取)。

+ +

網頁開發者不能控制使用者可能使用何種瀏覽器來檢視一個網站 — 瀏覽器與用戶端程式有著不同層度的相容性,並且用戶端程式的挑戰之一是如何妥善地處理瀏覽器支援的差異。

+ +

伺服端程式碼可以為任何程式語言 — 例如有名的伺服端網頁語言包括PHP、Python、Ruby、C#與NodeJS(JavaScript)。該伺服端程式碼擁有完整的作業系統存取權限,而且開發者能夠選擇他們想要的程式語言(以及特定版本)。

+ +

開發者們通常使用網頁框架web frameworks)撰寫程式碼。網頁框架為功能函式、物件、規則與其他程式碼的集合,旨在解決常見問題、加速開發並簡化在特定域中面臨到的不同類型的任務。

+ +

再者,儘管用戶端與伺服端程式碼都使用框架,但會因為非常不同的域,而使得框架也不同。用戶端網頁框架簡化佈局與呈現的任務,而伺服端網頁框架則提供大量"通用"的網頁伺服器功能,否則你可能必須要自己實現(例如:對sessions的支援、對使用者認證的支援、簡易資料庫存取、樣板庫等)。

+ +
+

Note: Client-side frameworks are often used to help speed up development of client-side code, but you can also choose to write all the code by hand; in fact, writing your code by hand can be quicker and more efficient if you only need a small, simple web site UI.

+ +

In contrast, you would almost never consider writing the server-side component of a web app without a framework — implementing a vital feature like an HTTP server is really hard to do from scratch in say Python, but Python web frameworks like Django provide one out of the box, along with other very useful tools.

+
+ +
+

在伺服端,你能做什麼?

+ +

伺服端程式設計是非常有用的,因為它讓我們有效地遞送替單個使用者量身訂做的資訊,從而創造更棒的使用者體驗。

+
+ +

如Amazon這樣的公司使用伺服端程式設計來建構產品搜尋結果、根據顧客偏好與過往購物習慣提供針對性的產品建議、簡化購物過程等。

+ +

銀行使用伺服端程式設計來儲存帳號資訊,並讓已授權用戶檢視與進行交易。其他服務如Facebook、Twitter、Instagram與Wikipedia使用伺服端程式設計來突顯、分享與控制使用者存取到感興趣的內容。

+ +

一些常見的伺服端程式設計使用案例與效益列舉如下。您將會注意到這當中會有些重疊的部分!

+ +

高效率資訊儲存與遞送

+ +

想像一下,在Amazon可以找到多少產品,或者說在Facebook上有多少文章?對各個產品或文章建立各別的靜態網頁完全是不切實際的。

+ +

伺服端程式設計反而是可以讓我們將資訊儲存至資料庫,並且動態建構及回傳HTML與其他型態的檔案(例如:PDF、圖片等)。它也可以藉由合適的用戶端網頁框架(利用這個方式可以降低在伺服器的處理負擔,亦減少需要被送出的大量資料)僅回傳資料({{glossary("JSON")}}、{{glossary("XML")}}等)來進行畫面渲染。

+ +

伺服器並不侷限於從資料庫發送資訊,還可以回傳軟體工具的結果或是來自通訊服務的資料。這些內容甚至可以針對到收到它的用戶裝置類型。

+ +

由於資訊存在於資料庫中,它可以輕易地與其他商業系統進行分享與更新(例如:當產品在線上或在店家中售完,店家可能會更新該產品的庫存資料庫)。

+ +
+

Note: Your imagination doesn't have to work hard to see the benefit of server-side code for efficient storage and delivery of information:

+ +
    +
  1. Go to Amazon or some other e-commerce site.
  2. +
  3. Search for a number of keywords and note how the page structure doesn't change, even though the results do. 
  4. +
  5. Open two or three different products. Note again how they have a common structure and layout, but the content for different products has been pulled from the database.
  6. +
+ +

For a common search term ("fish", say) you can see literally millions of returned values. Using a database allows these to be stored and shared efficiently, and it allows the presentation of the information to be controlled in just one place.

+
+ +

客製化的使用者體驗

+ +

伺服器能保存及使用關於用戶的資訊,來提供一個方便且量身訂做的使用者體驗。例如,許多網站儲存信用卡資料讓這些資料無須再重新輸入。網站如Google Maps能使用已儲存或目前位置來提供導航資訊與搜尋或旅行歷史紀錄,以便於搜尋結果中突顯在地店家。

+ +

一個使用者習慣更深層的分析,可以使用在預測他的興趣以及更進一步客製回應與提醒,例如在地圖中提供你可能想去看得過去遊歷過的或是熱門的地點列表。

+ +
+

Note: Google Maps saves your search and visit history. Frequently visited or frequently searched locations are highlighted more than others.

+ +

Google search results are optimized based on previous searches.

+ +
    +
  1.  Go to Google search.
  2. +
  3.  Search for "football".
  4. +
  5.  Now try typing "favourite" in the search box and observe the autocomplete search predictions.
  6. +
+ +

Coincidence? Nada!

+
+ +

控制內容存取

+ +

伺服器端程式設計允許網站限制僅能由已授權的使用者存取,並提供資訊給那些只被允許觀看的使用者。

+ +

真實世界案例包括:

+ + + +
+

Note: Consider other real examples where access to content is controlled. For example, what can you see if you go to the online site for your bank? Log in to your account — what additional information can you see and modify? What information can you see that only the bank can change?

+
+ +

儲存session/state資訊

+ +

伺服器端程式設計允許開發者利用sessions — 基本上,就是一個機制讓伺服器儲存目前的使用者資訊,並且基於這些資訊發送不同的回應。

+ +

例如,這允許網站了解一個使用者先前已登入過,以及將訂購歷史紀錄在他們的電子郵件中顯示連結,或者也許會儲存一個基本的遊戲狀態,讓使用者能再次回到網站的同時,拿回他們留在網站的資訊。

+ +
+

Note: Visit a newspaper site that has a subscription model and open a bunch of tabs (e.g. The Age). Continue to visit the site over a few hours/days. Eventually, you will start to be redirected to pages explaining how to subscribe, and you will be unable to access articles. This information is an example of session information stored in cookies.

+
+ +

提醒與溝通

+ +

伺服器能透過網站本身或經由電子郵件、SMS、即時通訊、影像或其他通訊服務,發送提醒訊息給一般或特定使用者。

+ +

一些範例包括:

+ + + +
+

Note: The most common type of notification is a "confirmation of registration". Pick almost any large site that you are interested in (Google, Amazon, Instagram, etc.) and create a new account using your email address. You will shortly receive an email confirming your registration, or requiring acknowledgment to activate your account.

+
+ +

資料分析

+ +

一個網站可能會收集很多包括使用者的資料:他們所搜尋的、他們所買的、他們所推薦的、他們在每個網頁停留的時間。伺服器端程式設計能根據資料分析以完善回應。

+ +

例如,Amazon與Google都根據過往搜尋(與購買)紀錄來廣告產品。

+ +
+

Note: If you're a Facebook user, go to your main feed and look at the stream of posts. Note how some of the posts are out of numerical order - in particular, posts with more "likes" are often higher on the list than more recent posts.

+ +

Also look at what kind of ads you are being shown — you might see ads for things you looked at on other sites. Facebook's algorithm for highlighting content and advertising can be a bit of a mystery, but it is clear that it does depend on your likes and viewing habits!

+
+ +

總結

+ +

恭喜,你已經到達關於伺服器端程式設計的第一篇文章的結尾。 

+ +

現在你已經學到伺服器端程式碼運作於網頁伺服器,他的主要任務是控制哪些資訊要發送給使用者(而用戶端程式碼主要掌握資料的結構與呈現給使用者)。

+ +

你也應該了解這是很有用的,當你身為伺服器端開發者時,因為它允許我們創建有效散播客製訊息與有些你可能會去做的好點子給單個使用者的網站。

+ +

最後,你應該了解伺服器端程式碼可以用很多種程式語言來撰寫,以及你應該使用網頁框架來讓整個程序變得更簡便。 

+ +

在未來的文章,我們將協助你選擇最佳的網頁框架,做為你的第一個網站;接著,我們將帶你更詳細了解主要的用戶端-伺服端的互動。

+ +

{{NextMenu("Learn/Server-side/First_steps/Client-Server_overview", "Learn/Server-side/First_steps")}}

+ +

In this module

+ + diff --git a/files/zh-tw/learn/server-side/index.html b/files/zh-tw/learn/server-side/index.html new file mode 100644 index 0000000000..c62f4e8aba --- /dev/null +++ b/files/zh-tw/learn/server-side/index.html @@ -0,0 +1,59 @@ +--- +title: 伺服端網站程式設計 +slug: Learn/Server-side +tags: + - Beginner + - CodingScripting + - Intro + - Landing + - Learn + - NeedsTranslation + - Server + - Server-side programming + - Topic + - TopicStub +translation_of: Learn/Server-side +--- +
{{LearnSidebar}}
+ +

動態網站伺服端網站程式設計是一連串有關如何建立動態網站的模塊:動態網站可以針對 HTTP 請求,發送客製化的資訊。這些模塊將介紹伺服端網站程式設計:還有以初學者的角度,來教你怎麼使用 Django (Python) 與 Express (Node.js/JavaScript) 來架設基本的動態網路程式。

+ +

大多數主流網站會使用伺服端技術,以根據需要呈現動態資料。例如說,來想想亞馬遜(Amazon)上架多少商品、還有臉書(Facebook)貼了多少動態。如果都用靜態頁面來呈現這些內容,開發就會毫無效率可言。因此,我們會使用靜態技術(HTMLCSSJavaScript)來顯示靜態模板;並在需要時,動態更新模板內的資料。一如你在逛亞馬遜時,看著五花八門的產品一般。

+ +

在當今的 Web development 的世界,我們強烈建議學習怎麼開發伺服端網站程式。

+ +

學習路徑

+ +

學習伺服端網站程式設計通常比用戶端網站程式設計簡單,因為動態網站比較傾向執行多次相似的操作(像是從資料庫擷取資料並放到頁面上、驗證用戶輸入的資料並存到資料庫、檢查登入用戶權限之類的)、使用框架建立網站能讓上述操作、以及其他常見操作變得簡單許多。

+ +

基本的程式概念(或是理解特定的語言)會很有用,但不是必須的。同樣地,精於用戶端網站程式設計不是必須,但它能在前端開發時,幫你做得更好。

+ +

首先你要知道「web 是怎麼作動的」。我們建議先看看這些文章:

+ + + +

有了基本觀念後,就可以開始去學習模塊章節的東西了。

+ +

模塊

+ +

本章節包含了以下模塊。你首先要從第一個模塊開始,再循序漸進,學習接下來的模塊。這些模塊將告訴你如何與訪間最熱門的其中兩個伺服器端框架共事。

+ +
+
伺服器端程式設計起步走
+
本模塊會提供與技術無關的伺服器資訊,像是「那什麼?」、「和用戶端有啥不同?」、「有用嗎?」之類的。本模塊也會概述一些比較熱門的伺服器端 web 框架、並告訴你如何選擇。最後,我們還會概述有關伺服器服務的安全性問題。
+
Django 網站框架 (Python)
+
Django 以 Python 寫成,是個非常熱門的伺服器端 web 框架。本模塊會講解 Django 是好框架的理由、如何建立開發環境、還有如何處理常見工作。
+
Express web framework (Node.js/JavaScript)
+
Express 以 JavaScript 寫成、並在 node.js 執行環境執行。它也是個非常熱門的伺服器端 web 框架。本模塊會講解一些有關本框架的重要優點、也同樣會講解如何建立開發環境、還有如何處理常見工作。
+
+ +

參見

+ +
+
不用框架的 Node 伺服器
+
如果不想用框架的話,這篇文章會告訴你如何使用純 Node.js 提供簡易的靜態檔案。
+
-- cgit v1.2.3-54-g00ecf