web本质
用Python专注于生成HTML文档。因为我们不希望接触到TCP连接、HTTP原始请求和响应格式,所以,需要一个统一的接口协议来实现这样的服务器软件,让我们专心用Python编写Web业务。这个接口就是WSGI:Web Server Gateway Interface。而wsgiref模块就是python基于wsgi协议开发的服务模块。
from wsgiref.simple_server import make_server from io import StringIO def application(environ,start_response): stdout = StringIO() #读取到内存 print("Hello world!", file=stdout) start_response("200 OK", [('Content-Type','text/plain; charset=utf-8')]) return [stdout.getvalue().encode('utf-8')] #必须以列表形式返回 server = make_server('127.0.0.1',8000,application) server.serve_forever()
socket实现web服务端
import socket sock = socket.socket() sock.bind(('127.0.0.1',8000)) //绑定ip和端口号 sock.listen(5) //最多监听5个 while True: print('server running') conn ,addr = sock.accept() //获取socket对象和ip地址信息 data = conn.recv(1024) //接受请求信息 conn.send(b'HTTP://1.1 200 OK <p><strong>hello world</strong></p>')
补充 with open('index.html','rb') as f:
data = f.read()
conn.send(b'HTTP://1.1 200 OK %s>',%data) //读取整个Html文件了
conn.close()
加上路由匹配的web版本
from wsgiref.simple_server import make_server
def index():
return 'index'
def login():
return 'login'
def routers():
urlpatterns = (
('/index/',index),
('/login/',login),
)
return urlpatterns
def RunServer(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
url = environ['PATH_INFO']
urlpatterns = routers() //接受环境变量,配置请求头
func = None
for item in urlpatterns: //匹配请求过来的url,找到对应的视图函数
if item[0] == url:
func = item[1]
break
if func:
return func()
else:
return '404 not found'
if __name__ == '__main__': //创建服务,监听
httpd = make_server('', 8000, RunServer)
print "Serving HTTP on port 8000..."
httpd.serve_forever()
Django框架遵循wsgi协议,底层采用socket socketserver select网络模型,利用操作系统的非阻塞和线程池等.django自带wsgi服务,并发默认是6个
线上部署一班采用c语言实现的uwsgi.