一個簡單的B/S架構
阿新 • • 發佈:2018-12-19
一,一個簡單的把py檔案與html檔案相互結合渲染在頁面上
import socket soc = socket.socket() # 傳送繫結的請求 soc.bind(('127.0.0.1', 8001)) # 服務端能接收的數量 soc.listen(5) while True: # 獲取從瀏覽器傳送來的資料 so, addr = soc.accept() # 每次接收資料的數量 data = so.recv(1024) so.send(b'HTTP/1.1 200 OK\r\nContent-Type:text/html\r\n\r\n') print(data) data = str(data, encoding='utf-8') # 把接收到的資料進行切分,獲得想得到的程式碼 position = data.split('\r\n')[0].split(' ')[1] if '/index' == position: # 進行路由切換 with open('index.html', 'rb') as f: da = f.read() so.send(da) else: so.send(b'404') so.close() ''' # 請求首行 # GET / HTTP/1.1\r\n # # 請求頭 # Host: 127.0.0.1:8001\r\n # Connection: keep-alive\r\n # Cache-Control: max-age=0\r\n # Upgrade-Insecure-Requests: 1\r\n # User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36\r\n # Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\n # Accept-Encoding: gzip, deflate, br\r\nAccept-Language: zh-CN,zh;q=0.9\r\n\r\n' # # 請求體 '''
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>index</h1> <hr> </body> </html>
二,四種套接的實現需求
伺服器啟動的主檔案py檔案
from wsgiref.simple_server import make_server from url import urls from views import error def run(env, response): print(env) # 響應,後面是響應頭 response('200 OK', [('Content-type', 'text/html')]) # 獲取路徑下面切換的/index position = env['PATH_INFO'] # 先定義函式為空,下面進行更改 func = None for url in urls: if position == url[0]: func = url[1] break if func: response = func(env) else: response = error(env) return [response.encode('utf-8')] if __name__ == '__main__': # 下面兩句是跑起來的固定搭配,缺一不可 ser = make_server('127.0.0.1', 8003, run) ser.serve_forever()
路由py檔案
from views import * urls = [ ('/index', index), ('/time', time), ('/test', test), ('/user', user), ]
路由裡面定義的方法py檔案
import datetime from jinja2 import Template import pymysql def index(env): # 切換html檔案,切換頁面 with open('templates/index.html')as f: data = f.read() return data def time(env): # 做一個動態的頁面,就是後臺的資料自己改變 ctime = datetime.datetime.now().strftime('%x %X') with open('templates/time.html', 'r')as f: data = f.read() data = data.replace('@@
[email protected]@', ctime) return data # 錯誤提示 def error(env): return '404' def text(env): with open('templates/test.html', 'r')as f: data = f.read() # 直接採用方法處理完資料放到模板()裡面 tem = Template(data) response = tem.rander(user={'name': 'nnn', 'age': 18}) return response def user(env): conn = pymysql.connect(host='127.0.0.1',post=3306,user='root', db='db2', password='123') cur = conn.cursor(pymysql.cursors.DictCursor) cur.execute('select * from user') dic = cur.fetchall() print(dic) with open('templates/user.html', 'r') as f: data = f.read() tem = Template(data) response = tem.render(user_list=dic) return response
方法裡面需要匯入的html檔案渲染到頁面,都放到templates中