1.写服务端
import datetime import socket #往网页内添加内容 #方式1 def index(): #读取网页 with open(r'D:untitledpython27.9login.html',"r" ,encoding='utf-8')as rb: date=rb.read(2048) tim = datetime.datetime.now() #替换网页内的####标签 date=date.replace("####", str(tim)) return date #方式2 def login(): import pymysql #导入数据库 conn=pymysql.connect(host='127.0.0.1',user='root',password='xzc123456',db='pycharm',charset='utf8') #把查出的的数据以json的格式显示 cursor=conn.cursor(cursor=pymysql.cursors.DictCursor) #查询数据库 sql='select * from class' #执行语句 cursor.execute(sql) #获取查询的内容 res=cursor.fetchall() #获取网页 with open(r'D:untitledpython27.9login.html','r' ,encoding='utf-8') as rp: date=rp.read() #导入渲染模板 from jinja2 import Template #获取模板 template=Template(date) #准备数据 data=template.render(users=res) return data #路由器 webpage=[ ('index',index), ('login',login), ] def run() sk=socket.socket() sk.bind(('127.0.0.1',5656)) sk.listen() while True: conn, addr=sk.accept() # date=conn.recv(2048 * 3) date=conn.recv(2048*3) #对请求进行分割 index=str(date).split(' ')[1].split('/')[1] conn.send(bytes('HTTP/1.1 200 ok ', encoding='utf-8')) print(index) func=None #分发请求 for item in webpage: if index==item[0]: func=item[1] break if func: res=func() else: res="404 not found" #以二进制的方式发送数据 conn.send(bytes(res, encoding='utf-8')) conn.close()