目录
用socket实现简单的web server
import socket
def main():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('localhost', 8000))
sock.listen(5)
while True:
# 等待浏览器访问
conn, addr = sock.accept()
# 接收浏览器发送来的请求内容
data = conn.recv(1024)
print(data)
# 给浏览器返回内容
conn.send(b"HTTP/1.1 200 OK\r\nContent-Type:text/html; charset=utf-8\r\n\r\n")
conn.send("电脑前的你长的真好看!".encode("utf-8"))
# 关闭和浏览器创建的socket连接
conn.close()
if __name__ == "__main__":
main()
基于wsgi开发一个WEB服务器
WSGI(Web Server Gateway Interface)是一种规范,它定义了使用python编写的web app(应用程序)与web server(socket服务端)之间接口格式,实现web app与web server间的解耦。
Python的wsgiref是基于WSGI规范封装的模块,我们可以在这个模块基础上开发我们的web server
1.基于wsgi的简单web
from wsgiref.simple_server import make_server
def run_server(environ, start_response):
print('hahahahaha', environ)
start_response("200 OK",[('Content-Type', 'text/html;charset=utf-8')])
return [bytes("<h1 style='color:red'>王训志是大傻逼</h1>", encoding='utf-8')]
s = make_server('localhost', 8000, run_server)
s.serve_forever()
2.基于wsgi的支持多url的web server
from wsgiref.simple_server import make_server
# 路由的分发器负责把url匹配到对应的函数
# 开发好对应的业务函数
# 一个请求来了之后,先走路由分发器,如果找到对应的function就执行,没找到就返回404
def book(environ, start_response):
print("book page")
start_response("200 OK", [('Content-Type', 'text/html;charset=utf-8')])
return [bytes("<h1 style='color:red'>book page</h1>", encoding='utf-8')]
def cloth(environ, start_response):
print("cloth page")
start_response("200 OK", [('Content-Type', 'text/html;charset=utf-8')])
return [bytes("<h1 style='color:blue'>cloth page</h1>", encoding='utf-8')]
def url_dispach():
urls = {
'/book': book,
'/cloth': cloth,
}
return urls
def run_server(environ, start_response):
print('hahahahaha', environ)
url_list = url_dispach() # 拿到所有url
request_url = environ.get("PATH_INFO")
print('request url', request_url)
if request_url in url_list:
func = url_list[request_url](environ, start_response)
return func # 真正返回数据给用户
else:
start_response("404 ", [('Content-Type', 'text/html;charset=utf-8')])
return [bytes("<h1 style='font-size:50px'>404, Page not found""</h1>", encoding='utf-8')]
s = make_server('localhost', 8000, run_server)
s.serve_forever()
3.基于wsgi的支持多url和图片的web server
from wsgiref.simple_server import make_server
import re
import os
# 路由的分发器负责把url匹配到对应的函数
# 开发好对应的业务函数
# 一个请求来了之后,先走路由分发器,如果找到对应的function就执行,没找到就返回404
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
def book(environ, start_response):
start_response("200 OK", [('Content-Type', 'text/html;charset=utf-8')])
data = '''
<h1>欢迎来到中中专区</h1>
<img src='/static/imgs/testing.jpg' />
<p>上中中专区,看尽天下小片</p>
'''
return [bytes(data, encoding='utf-8')]
def cloth(environ, start_response):
print("cloth page")
start_response("200 OK", [('Content-Type', 'text/html;charset=utf-8')])
return [bytes("<h1 style='color:blue'>cloth page</h1>", encoding='utf-8')]
def url_dispach():
urls = {
'/book': book,
'/cloth': cloth,
}
return urls
def img_handle(request_url):
'''
:param request_url: /static/imgs/testing.jpg
:return:
'''
img_path = re.sub("/static/", "/static_data/", request_url)
img_abs_path = "%s%s" % (BASE_DIR, img_path)
if os.path.isfile(img_abs_path):
f = open(img_abs_path, 'rb')
data = f.read() # 图片文件内容
return [data, 0]
else:
return [None, 1]
def run_server(environ, start_response):
print('hahahahaha', environ)
url_list = url_dispach() # 拿到所有url
request_url = environ.get("PATH_INFO")
print('request url', request_url)
if request_url in url_list:
func = url_list[request_url](environ, start_response)
return func # 真正返回数据给用户
elif request_url.startswith("/static/"): # 代表 是图片
img_data, img_status = img_handle(request_url)
if img_status == 0:
start_response("200 OK", [('Content-Type', 'text/jpeg;charset=utf-8')])
return [img_data, ]
else:
start_response("404 ", [('Content-Type', 'text/html;charset=utf-8')])
return [bytes("<h1 style='font-size:50px'>404, Page not found""</h1>", encoding='utf-8')]
s = make_server('localhost', 8001, run_server)
s.serve_forever()
Web框架的本质
- 1.浏览器是socket客户端,网站是socket服务端
- 2.wsgi,是一个规范,wsgiref实现了这个规范并在其内部实现了socket服务端
- 3.根据 url 的不同执行不同函数,即:路由系统
- 4.函数,即:视图函数
- 5.图片、css、js文件 统一称为静态文件,需要读取内容直接返回给用户浏览器