1. 程式人生 > >django入門篇之( web應用)

django入門篇之( web應用)

--------------------------------------------------------------------

本文目錄

回到目錄

一 Web應用程式是什麼

Web應用程式是一種可以通過Web訪問的應用程式,程式的最大好處是使用者很容易訪問應用程式,使用者只需要有瀏覽器即可,不需要再安裝其他軟體

應用程式有兩種模式C/S、B/S。C/S是客戶端/伺服器端程式,也就是說這類程式一般獨立執行。而B/S就是瀏覽器端/伺服器端應用程式,這類應用程式一般藉助IE等瀏覽器來執行。WEB應用程式一般是B/S模式。Web應用程式首先是“應用程式”,和用標準的程式語言,如C、C++等編寫出來的程式沒有什麼本質上的不同。然而Web應用程式又有自己獨特的地方,就是它是基於Web的,而不是採用傳統方法執行的。換句話說,它是典型的瀏覽器/伺服器架構的產物。

Web應用程式的優點

  • 網路應用程式不需要任何複雜的“展開”過程,你所需要的只是一個適用的瀏覽器;
  • 網路應用程式通常耗費很少的使用者硬碟空間,或者一點都不耗費;
  • 它們不需要更新,因為所有新的特性都在伺服器上執行,從而自動傳達到使用者端;
  • 網路應用程式和伺服器端的網路產品都很容易結合,如email功能和搜尋功能;
  • 因為它們在網路瀏覽器視窗中執行,所以大多數情況下它們是通過跨平臺使用的 (例如Windows,Mac,Linux等等)

Web應用程式的缺點

  • 網路應用程式強調瀏覽器的適用性。如果瀏覽器方沒有提供特定的功能,或者棄用特定的平臺或作業系統版本(導致不適用),就會影響大量使用者;
  • 網路應用依靠網際網路遠端伺服器端的應用檔案。因此,當連接出問題時,應用將不能正常使用。
  • 許多網路應用程式不是開源的,只能依賴第三方提供的服務,因此不能針對使用者定製化、個性化,而且大多數情況下使用者不能離線使用,因而損失了很多靈活性;
  • 它們完全依賴應用服務商的可及性。如果公司倒閉,伺服器停止使用,使用者也無法追索以前的資料。對比而看,即使軟體製造商倒閉了,傳統的安裝軟體也可以繼續執行,儘管不能再更新或有其他使用者服務;
  • 相似地,提供方公司對軟體和其功能有了更大的控制權。只要他們願意就能為軟體新增新特性,即使使用者想等bugs先被解決再更新。跳過較差的軟體版本也不可能了。公司可以強加不受歡迎的特性給使用者,也可以隨意減少頻寬來削減開支。
  • 公司理論上可以檢索任何的使用者行為。這有可能引起隱私安全問題。

B/S架構優點

瀏覽器/伺服器架構(Browser/Server,簡稱B/S)能夠很好地應用在廣域網上,成為越來越多的企業的選擇。瀏覽器/伺服器架構相對於其他幾種應用程式體系結構,有如下3方面的優點:
  • 這種架構採用Internet上標準的通訊協議(通常是TCP/IP協議)作為客戶機同伺服器通訊的協議。這樣可以使位於Internet任意位置的人都能夠正常訪問伺服器。對於伺服器來說,通過相應的Web服務和資料庫服務可以對資料進行處理。對外採用標準的通訊協議,以便共享資料。
  • 在伺服器上對資料進行處理,就處理的結果生成網頁,以方便客戶端直接下載。
  • 在客戶機上對資料的處理被進一步簡化,將瀏覽器作為客戶端的應用程式,以實現對資料的顯示。不再需要為客戶端單獨編寫和安裝其他型別的應用程式。這樣,在客戶端只需要安裝一套內建瀏覽器的作業系統,直接安裝一套瀏覽器,就可以實現伺服器上資料的訪問。而瀏覽器是計算機的標準裝置

總結一下,本質上:瀏覽器是一個socket客戶端,伺服器是一個socket服務端

回到目錄

二 基於SOCKET寫一個web應用

 py檔案

複製程式碼
import socket

def server_run():
    soc = socket.socket()
    soc.bind(('127.0.0.1', 8008))
    soc.listen(5)
    while True:
        conn, addr = soc.accept()
        recv_data = conn.recv(1024)
        print(recv_data)
        # 1 直接在send裡寫,傳送給客戶端
        # conn.send(b'HTTP/1.1 200 OK\r\n\r\n<h1>hello web</h1><img src="https://gss2.bdstatic.com/9fo3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike92%2C5%2C5%2C92%2C30/sign=5e3814acf9edab64607f4592965fc4a6/14ce36d3d539b600c0c465d0eb50352ac65cb74b.jpg"></img>')
        #2 開啟一個html檔案,傳送給客戶端
        # with open('index.html','r',encoding='utf-8') as f:
        #     data=f.read()
        # conn.send(('HTTP/1.1 200 OK\r\n\r\n%s'%data).encode('utf-8'))
        # 3 動態網頁,字串替換
        import time
        now=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        print(now)
        with open('index.html','r',encoding='utf-8') as f:
            data=f.read()
        data=data.replace('@@@',now)
        conn.send(('HTTP/1.1 200 OK\r\n\r\n%s'%data).encode('utf-8'))
        conn.close()

if __name__ == '__main__':
    server_run()
複製程式碼

index.html 檔案

複製程式碼
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h2>@@@</h2>

<img src="https://gss2.bdstatic.com/9fo3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike92%2C5%2C5%2C92%2C30/sign=5e3814acf9edab64607f4592965fc4a6/14ce36d3d539b600c0c465d0eb50352ac65cb74b.jpg" alt="">
</body>
</html>
複製程式碼 回到目錄

 三 手擼簡單web框架

  WebServer

'''
a socket服務端
b 根據url不同返回不同的內容
url---檢視函式
c 字串返回給使用者
特殊字元替換

Web框架種類:
a b c Tornado
別人的a b c django(a用的wsgiref)
別人a b 別人c flask(c用的jinja2)
另一種分類:
Django和其它

'''
import socket

import pymysql
def index(request):
return '<img src="https://gss2.bdstatic.com/9fo3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike92%2C5%2C5%2C92%2C30/sign=5e3814acf9edab64607f4592965fc4a6/14ce36d3d539b600c0c465d0eb50352ac65cb74b.jpg"></img>'


def login(request):
with open('login.html','r',encoding='utf-8') as f :
data=f.read()
return data
def time(request):
import datetime
now=datetime.datetime.now().strftime('%Y-%m-%d %X')
with open('time.html','r',encoding='utf-8') as f :
data=f.read()
data=data.replace('@@[email protected]@',now)
return data
def user_list(request):
# 建立連線
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='lqz')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("select id,name,password from user")
user_list = cursor.fetchall()
cursor.close()
conn.close()
tr_list=[]
for row in user_list:
tr='<tr><td>%s</td><td>%s</td><td>%s</td></tr>'%(row['id'],row['name'],row['password'])
tr_list.append(tr)


with open('user_list.html','r',encoding='utf-8') as f:
data=f.read()
data=data.replace('@@[email protected]@',''.join(tr_list))
return data

def user_list_new(request):
# 建立連線
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='lqz')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("select id,name,password from user")
user_list = cursor.fetchall()
cursor.close()
conn.close()
with open('user_list_new.html','r',encoding='utf-8') as f:
data=f.read()
from jinja2 import Template
template=Template(data)
response=template.render(user_list=user_list)
# response=template.render({'user_list':user_list})
return response


urls = [
('/index', index),
('/login', login),
('/time', time),
('/user_list', user_list),
('/user_list_new', user_list_new),
]


def run():
soc = socket.socket()
soc.bind(('127.0.0.1', 8006))
soc.listen(5)
while True:
conn, port = soc.accept()
data = conn.recv(1024)
# data=data.decode('utf-8')
print(data)
data = str(data, encoding='utf-8')
request_list = data.split('\r\n\r\n')
head_list = request_list[0].split('\r\n')
method, url, htt = head_list[0].split(' ')
# conn.send(b'hello web')
conn.send(b'HTTP/1.1 200 OK \r\n\r\n')
print(url)
func_name = None
for u in urls:
if url == u[0]:
func_name = u[1]
break
if func_name:
response = func_name(data)
else:
response = '404 not found'

conn.send(response.encode('utf-8'))
conn.close()


if __name__ == '__main__':
run()

WebServer

  login.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>

<form action="">
<p>使用者名稱:<input type="text"></p>
<p>密碼:<input type="password"></p>


</form>
</body>
</html>

login.html

  time.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>


@@[email protected]@
</body>
</html>

time.html

  user_list.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用者列表</title>
</head>
<body>

<table border="1">
<thead>
<tr>
<th>id</th>
<th>使用者名稱</th>
<th>密碼</th>
</tr>
</thead>
<tbody>
@@[email protected]@
</tbody>


</table>

</body>
</html>

user_list.html

  user_list_new

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用者列表</title>
</head>
<body>
<table border="1">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>password</th>
</tr>
</thead>
<tbody>

{% for user in user_list%}
<tr>
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td>{{user.password}}</td>
</tr>
{%endfor%}


</tbody>


</table>

</body>
</html>

user_list_new