web 框架本质 - Web应用本质上就是一个socket服务端,而用户的浏览器就是一个socket客户端。
HTTP协议
HTTP协议介绍HTTP协议对收发消息的格式要求每个HTTP请求和响应都遵循相同的格式,一个HTTP包含Header和Body两部分,其中Body是可选的。HTTP响应的Header中有一个 Content-Type表明响应的内容格式。它的值如text/html; charset=utf-8。text/html则表示是网页,charset=utf-8则表示编码为utf-8。
socket 服务端 基础版-------------------------import socketsk = socket.socket()sk.bind(('127.0.0.1',8002))sk.listen()while True: conn,addr = sk.accept() data = conn.recv(8096) print(data) conn.send(b'HTTP/1.1 200 ok\r\nk1: v1\r\n\r\n') conn.send(b'ok!
') conn.close() ---------------------------------- 根据不同路径返回不同内容
while True: conn,addr = sk.accept() data = conn.recv(8096) data = data.decode() url = data.split()[1] conn.send(b'HTTP/1.1 200 ok\r\nk1: v1\r\n\r\n') if url == '/sx': conn.send(b'11') elif url == '/bj': conn.send(b'22') else: conn.send(b'not found!') conn.close() ----------------------------------- --def 函数版---
import socket sk = socket.socket() sk.bind(('127.0.0.1',8002)) sk.listen() def sx(url): ret = 'nihao - {}'.format(url) return ret.encode() def bj(url): ret = 'huairen - {}'.format(url) return ret.encode() while True: conn,addr = sk.accept() data = conn.recv(8096) data = data.decode() url = data.split()[1] conn.send(b'HTTP/1.1 200 ok\r\nk1: v1\r\n\r\n') if url == '/sx': ret = sx(url) elif url == '/bj': ret = bj(url) else: ret = b'not found' conn.send(ret) conn.close() ----------------------------------- 进阶列表版
import socket sk = socket.socket() sk.bind(('127.0.0.1',8002)) sk.listen() def sx(url): ret = 'nihao - {}'.format(url) return ret.encode() def bj(url): ret = 'huairen - {}'.format(url) return ret.encode() # 定义一个地址和函数的对应关系的列表 list1 = [('/sx',sx),('/bj',bj)] while True: conn,addr = sk.accept() data = conn.recv(8096) # 接收数据 data = data.decode() url = data.split()[1] # 获取url conn.send(b'HTTP/1.1 200 ok\r\nk1: v1\r\n\r\n') func = None for i in list1: if url == i[0]: func = i[1] break if func: ret = func(url) else: ret = b'not found' conn.send(ret) conn.close() ----返回html网页------------------
def index(url): with open('index.html', 'rb') as f: ret = f.read() return ret list1 = [('/sx',sx),('/index',index)] --------返回一个动态页面------------
def timer(url): now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()) with open('time.html','r',encoding='utf-8') as f: data = f.read() data = data.replace('@@time@@',now) return data.encode('utf-8') list1 = [('/sx',sx),('/index',index),('/timer',timer)]
"""根据URL中不同的路径返回不同的内容--函数进阶版返回HTML页面让网页动态起来wsgiref模块版"""--------------------------------------------------from wsgiref.simple_server import make_serverdef index(url): with open('index.html','r',encoding='utf-8') as f: s = f.read() return bytes(s,encoding='utf-8')def timer(url): import time with open('time.html','r',encoding='utf-8') as f: s = f.read() s = s.replace('@@time@@',time.strftime("%Y-%m-%d %H:%M:%S")) return bytes(s,encoding='utf-8')list1 = [('/index/',index),('/time/',timer)]def run_server(environ,start_response): #设置http 响应的状态码和头信息 start_response('200 OK',[('Content-Type', 'text/html;charset=utf8'),]) url = environ['PATH_INFO'] #取到用户输入的url func = None for i in list1: if i[0] == url: func = i[1] break if func: response = func(url) else: response = b'404 not found!' return [response,]if __name__ == '__main__': httpd = make_server('127.0.0.1',8888,run_server) print('我在8888等你呦...') httpd.serve_forever()
------------引用第三方 jinja2---------- from wsgiref.simple_server import make_serverfrom jinja2 import Templatedef index(url): #读取html文件 with open('index2.html','r',encoding='utf-8') as f: data = f.read() temp = Template(data) #生成模板文件 ret = temp.render({ 'name':'alex','hobby_list': ['抽烟', '喝酒', '烫头']})#把数据填充到模板中 return bytes(ret,encoding='utf-8')def home(url): with open('home.html','r',encoding='utf-8') as f: s = f.read() return bytes(s,encoding='utf-8')list1 = [('/index/',index),('/home/',home)]def run_server(environ,start_response): #设置http 响应的状态码和头信息 start_response('200 OK',[('Content-Type', 'text/html;charset=utf8'),]) url = environ['PATH_INFO'] #取到用户输入的url func = None for i in list1: if i[0] == url: func = i[1] break if func: response = func(url) else: response = b'404 not found!' return [response,]if __name__ == '__main__': httpd = make_server('127.0.0.1',8888,run_server) print('我在8888等你呦...') httpd.serve_forever()