一,一个简单的把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('@@time@@', 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中