ClientServerOverview

KY
9 min readMay 18, 2022

CSR紀錄理解過程

ClientServerOverview

Now that know the purpose and potential benefits of server-side programming we’re going to examine in detail what happens when a server receives a “dynamic request” from a browser.

目前所知的目標和潛力優點 server-side 編程,我們將會檢驗細節發生什麼當伺服器接收到一個來自瀏覽器的動態的要求.

As most website server-side code handles requests and responses in similar ways, this will help you understand what you need to do when writing most of your own code.

大部分的 server-side 程式,用相同的方式 控制要求和反應,這將會幫助你了解什麼你什麼時候需要撰寫大部分你自己的程式碼.

Prerequisites 預處理: 基本的電腦識別. 基本的認知對於什麼是 web server.

Objective: 去了解 client-server 再動態網頁的交互處理作用, 並且在特定的操作需要去執行 server-side 程式碼.

There is no real code in the discussion because we haven’t yet chosen a web framework to use to write our code! 這裡不會有實際的程式碼在這次討論中,我們還沒有選擇正式的框架去撰寫.

This discussion is however still very relevant, because the described behavior must be implemented by your server-side code, irrespective of which programming language or web framework you select.

這個討論仍然是十分相關的,因為我們描述行為必須被你的 server-side code 執行,無關任何你選擇的框架語言.

Web servers and HTTP(a primer)

「網頁瀏覽器」與「網頁伺服器」透過 HTTP (Hyper Text Transfer Protocol)溝通.當你在網頁上面點擊一個按鈕, 送出一張表單, 或是跑一個搜尋, 瀏覽器會送出一個 HTTP Request 給伺服器.

這個 request 包含:

  • 一個 URL 識別目標伺服器 和 資源 (比如. HTML 資料, 特定的資料指向伺服器, 或是跑一個工具)
  • 一個方法定義了要求的動作(例如: 去得到一些檔案, 或去儲存一個檔案, 或更新一些資料). 不同的方法和動詞 和他們的關聯動作在監聽瀏覽器.
  • Get : Get 特定的資源 (比如: HTML 資料包含資訊關於一個產品, 或一系列的產品)
  • POST : 創造一個新的資源 (比如: 增加新的文章到維基百科, 和data base 增加新的接觸)
  • HEAD : 得到 metadata資訊關於特定的資源,沒有 body 相較於 Get.你可能會使用 HEAD request 去找到最近一次的資源更新,並且運用 Get 去下載資源如果資料改變的話.
  • PUT : 更新已經存在的資源(或創造一個新的,如果完全不存在過就創建)
  • Delete : 刪除特定資源
  • TRACE, OPTION, CONNECT, PATCH : 這些動詞較少使用,所以在這邊不多做說明.
  • 額外的資訊可以被編譯藉由 request (例如, HTML form data). 資訊可以被編譯成:
  • URL parameters : GET request 編譯資訊在 URL 發給伺服器藉由增加「名稱、值」一對/一組,在最尾端.(例如 http://example.com?name=Fred&age=11.)你會先有一個問號符號 (?) 去區隔剩餘的 URL 和 URL parameters, 一個等於符號 (=)去區隔每一個名稱,來自關聯的值。和ampersand (&)區和另外一組。URL parameters 是天生的”不安全”,當他們可以變更藉由使用者改變然後重新送出.當 result URL parameters/GET request 不用於更新服務器上數據的請求.
  • POST : data post. POST request 新增新的資源,資料對於編譯和 request body.
  • Client side cookies. Cookies contains session data about the client, 包含 keys 和伺服器可以去決定 他們的登入狀況和授權權限/准許去獲取資源.

Web servers wait for client request message, progress them when they arrive, and reply to the web browser with an HTTP Response message.The response contains an HTTP Response status code indicating whether or not the request succeeded (eg, “200 OK” for success, “404 Not found” , “403 Forbidden”). The body of successful response to a GET request would contain the requested resource.

When an HTML page is returned it is rendered by the browser. As part of processing the browser may discover links to other resources(e.g. an HTML page usually references JavaScript and CSS page), and will send separate HTTP Requests to download these files.

Both static and dynamic website (discussion in the following sections) use exactly the same communication protocol/patterns.

GET request/response example

You can make a simple GET request by clicking on a link or searching on site (like a search engine homepage).For example, the HTTP request that is sent when you perform履行 a search below以下 (it will not be identical完全相同的 because parts of the message depend on your bowser/setup)

The request

Each line of the request contains information about it . The first part is called the header, and contains useful information about the request, in the same way that an HTML head contains useful information about an HTML document (but not the actual content itself, which is in the body):

The first and second lines contains most of the information we talked about above:

  • The type of request (GET).
  • The target resource URL(/en-US/search)
  • The URL parameters (q=client%2Bserver%2Boverview&topic=apps&topic=html&topic=css&topic=js&topic=api&topic=webdev).
  • The target / host website (developer.mozilla.org)
  • The end of the first line also including a short string identifying the specific protocol version (HTTP/1.1)

The final line contain information about the client-side cookies — you can see in this case the cookies includes an id for managing sessions(Cookie: sessionid=6ynxs23n521lu21b1t136rhbv7ezngie; …)

The remaining lines contain information about the browser used and the sort of responses it can handle. For example, you can see here that:

  • My bowser (User-Agent) is Mozilla Firefox
  • It can accept gzip compressed information
  • It can accept the specified set of the web page that contained the link to this resource (i.e. the origin of the request, https://developer.mozilla.org/en-US/)

HTTP requests can also have a body, but it is empty in this case.

The response

The first part of the response for this request is shown below.The header contains information like the following:

  • The first line includes the response code 200 ok, which tells us that the request succeeded. 回應200表示ok
  • We can see that the response is text/html formatted .可以看到回應被重新初始化.
  • We can also see that it uses the UTF-8 character set.
  • The head also tells us how big it is.

At the end of the message we see the body content — which contains the actual HTML returned by the request.

The re remainder of the response header includes information about the response (e.g. when it generated), the server, and how it expects the browser to handle the page (e.g. the X-Frame-option: DENY line tells the browser not to allow this page to be embedded in an <iframe>in another site.)

POST request/response example

An HTTP POST is made when you submit a form containing information to be saved on the server.

The request

The text below shows the HTTP request made when a user submits new profile details on this site.The format of the request is almost the same as the GET request example shown previously, though the first line identifiles this request as a POST.

Static sites 靜止

The static site is one that the same hard coded content from the server whenever a particular resource is requested. So for example if you have a page about a product at /static/myproduct1.html, this same page will be returned to every user. If you add another similar product to your site you will need to add another page.(e.g. myproduct2.html)and so on.This can start really inefficient 效率低下 — what happens when you get to thousands of pages? You would repeat a lot of code across each page (the basic page template, structure, etc…) and if you wanted anything about the page structure — like add a new “related products” section for example — then you’d have to change every page individually.

Let’s recap on how this works, by looking again at the static architecture diagram we looked at in the last article.

When a user wants to navigate導航 to a page, the browser send the HTTP GET request specifying the URL of its HTML page. The server retrieves the requested檢索 the requested document from its files system and returns an HTTP response containing the document and an HTTP Response status code of “200 OK”(indicating success).The server might be return different status code , for example “404 not found” if the file is not present on the server, or “301 Moved Permanently” if the file exists but has been redirected重定向 to a different location.

The server for a static site will only ever need to process過程 GET request, because the server doesn’t 不 store儲存 any modifiable任何可修改 data資料. It’s also doesn’t changed it’s responses based on HTTP Request data (e.g. URL parameters or cookies).

Understanding how static sites work is nevertheless useful when learning server-side programing, because dynamic sites handle request for static files (CSS , JavaScript, static images , etc.)in exactly the same way.

Dynamic site

A dynamic site is one that can generate and return content based on the specific request URL and data (rather than always returning the same hard-coded file for a particular URL).Using the example of product site, the server would receiving an HTTP GET Request for product, the server determines the product ID fetches the data from the database, and the constructs the HTML page for the response by inserting the data into HTML template. This has major advantages over a static site:

使用 Data base 使得產品資訊被存取更有效率,用簡單的可擴展的、可修改的、可被搜尋的

使用HTML templates 使得 HTML 結構很簡易被更改,因為只需要在同一個地方做改變,在單一的 templates 底下,以及不需要通過數千萬個可能的潛在的靜態頁面.

Anatomy of a dynamic request 解剖動態需求

這邊會逐步地講解 “動態” HTTP 要求以及回應的循環,建立在我們看到的文章畫面所有細節.為了保持的的真實性我們將會使用 context sport-team 管理網站.在那裡 教練可以選擇,隊伍的名子、隊伍的大小在HTML頁面上,並得到回饋在下場比賽最好的 列隊方式。

下方是網站的樣子,有標籤標示「執行數字」順序,當她決定了最佳的列隊方式。(這就是 HTTP request / HTTP Response) the Database, which contains information about players, teams, coaches, and their relationship, and HTML templates.

encode: 編碼

After the 教練送出名子和數字,序列操作將會:

  1. 瀏覽器創建了HTTP GET request to server using the base URL for the resource (/best)並編碼,名稱和對號(e.g. /best?team=my_team_name&show=11)也可以是(e.g. /best/my_team_name/11/)A GET request 是唯一 fetching 獲取 data (不是動態獲取)
  2. 網頁伺服器檢測到request是 ”動態” 的 and forward it to the Web Application for processing(the web server 決定如何處理不同的 URLs 基於比對規則定義設定)
  3. 網頁應用程式定義了意圖 of 要求,the best team list,based on the URL (/best/)且從 URL 要求了名稱和數字. finds out required team name and number of players from URL. The Web Application get then gets the required information from database. (Using additional parameters to define which players are “best”, and possibly also getting the identity of logged in coach from a client-side cookie).
  4. The Web Application dynamically creates an HTML page by putting the data (from the Database)into placeholders inside an HTML template.
  5. The Web Application return the generated HTML to the web browser (via the web server), along with HTTP status of 200 success. If anything prevents the HTML from being returned then the Web Application will return another code — for example “404” to indicate the team does not exist.
  6. The Web browser will then start to process the returned HTML , sending separate request to get any other CSS or JavaScript files that it references (see step 7).
  7. The Web server load static files from the file system and returns them to the browser directly (again, correct file handling is base on config rules and URL pattern matching).

An operation to update a record in the database would be handled similarly, expect that like any database update, the HTTP request from the bowser should be encoded as a POST request.

Doing other work

A Web Application’s job is receive HTTP request and return HTTP responses.While interacting with a database to get or update information are very common tasks, the code may do other things at the same time, or not interact with a database at all.

A good example of an additional task that a web Application might perform would be sending an Email to confirm their registration with site.The site might also perform logging or other operations.

Returning something other than HTML

Server-site website code dose not have to return HTML snippets/files in the response.It can instead dynamically create and return other types of files (text, PDF, CSV, etc.) or even data (JSON, XML, etc.)

The idea of returning data to a web browser so that it can dynamically update its own content (AJAX)has been around for quite a while.More recently “Single-page apps” have become popular, where the whole website is written with a single HTML file that is dynamically updated when needed.Website created using this style of application push a lot of computational cost from the server to the web browser, and can result in website that appear to behave a lot more like native apps (highly responsive , etc.).

web框架簡化了 server端的網頁編程

server-side web frameworks make writing code to handle the operations described above much easier.

Server-side網頁框架使得撰寫程式碼去操作描述下更加容易。

其中一個重要的操作彰顯提供簡單的機制去媒合URLs對於不同的資源頁面對於不同的資源頁面去具體的處理函式處理程序。這使得更容易快寶持成是馬關連和每一個茲元的分離。這也是使得更好維護的條件之一,因為你可以透過URL去傳遞特定的feature 在同一個地方,不需要去改變控制函式。

參考以下用python 寫的兩個views,兩個函式去控制兩個URL。

  • 第一個pattern 確保HTTP request和資源URL /best將會被命名做 index() 在views模版裡。
  • 一個 request 包含 “/best/junior",將改為 junior() view function.

網頁框架也使得從database獲取資訊更加容易,我們的結構在模板裡面定義好了,是python方式定義了database潛在的潛在的儲存範圍。如果我們有一個模組叫做 “team_type”然而我們會用簡單的搜尋語法去得到特定的回傳。

底下是範例,a list of all teams that have the exact (case sensitive) team_type of “junior” — note the format: filed name (team_type)following by double underscore, and then the type of match to use (in this case exact).There are many other types of matches and we can daisy chain them. We can also control the order and the number of results returned.

在 junior 函式執行之後,得到一系列的 junior teams, 這被叫做 render function, 透過原始得http request,一個HTML template , and a “context”物件定義了資訊去背包含模板。render函式定義被用來產生HTML,使用 context 和 HTML returns 一個 HttpResponse 物件。

顯然網頁框架可以幫助許多的工作。我們將討論大多主流框架的選擇在下一篇文章。

總結

這個章節的重點是讓他總覽一遍總體的server-side履行過程,並了解一些server-side 網頁框架可以使其簡單的做法。

接下來我們將幫助你選擇框架。

--

--