集成解析动态请求的功能
浏览器请求的资源:静态资源 + 动态资源
静态资源:写好的固定界面http/css/js/png/jpg等
动态资源:重新生成制作的界面
# coding:utf-8
import socket
import re
import multiprocessing
import time
class WSGIServer(object):
def __init__(self):
# 1.创建套接字
self.tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 2.绑定地址
self.tcp_server_socket.bind(('', 7890))
# 3.变为监听套接字
self.tcp_server_socket.listen(128)
def service_client(self, new_socket):
# 1.接收浏览器发送过来的请求,即http请求
# GET / HTTP/1.1
requset = new_socket.recv(1024).decode('utf-8')
requset_lines = requset.splitlines()
print(requset_lines)
file_name = ''
ret = re.match(r'[^/]+(/[^ ]*)', requset_lines[0])
if ret:
file_name = ret.group(1)
if file_name == "/":
file_name = '/index.html'
# 2.返回http格式的数据给浏览器
# 2.1 如果请求的资源部署以.py结尾,那么就认为是静态资源(http/css/js/png/jpg等)
if not file_name.endswith('.py'):
try:
f = open('./html' + file_name, 'rb')
except:
response = 'HTTP/1.1 404 NOT FOUND\r\n'
response += '\r\n'
response += '---------file not found---------'
new_socket.send(response.encode('utf-8'))
else:
html_content = f.read()
response = 'HTTP/1.1 200 OK\r\n'
response += '\r\n'
# header发送给服务器
new_socket.send(response.encode('utf-8'))
# body发送给服务器
new_socket.send(html_content)
else:
# 2.2 如果是以.py结尾,那么就认为是动态资源的请求
header = 'HTTP/200 OK\r\n'
header += '\r\n'
body = 'hhaha %s' % time.ctime()
response = header + body
# 发送response给浏览器
new_socket.send(response.encode('utf-8'))
def run_forever(self):
while True:
# 等待客户端连接
new_socket, client_addr = self.tcp_server_socket.accept()
p = multiprocessing.Process(target=self.service_client, args=(new_socket,))
p.start()
new_socket.close()
self.tcp_server_socket.close()
def main():
'''控制整体,创建一个web服务器对象,然后调用这个对象的run_forever方法运行'''
wsgi_server = WSGIServer()
wsgi_server.run_forever()
if __name__ == '__main__':
main()
将web服务器和逻辑处理的代码分开
新建一个模块mini_frame
# coding:utf-8
import time
# 登陆
def login():
return 'welcome to login......time: %s' % time.ctime()
# 注册
def register():
return 'welcome to register......time: %s' % time.ctime()
# 介绍
def profile():
return 'welcome to profile......time: %s' % time.ctime()
def application(file_name):
if file_name == '/login.py':
login()
elif file_name == 'register.py'
register()
elif file_name == 'profile'
profile()
else:
return 'not found you page....'
解耦
else:
# 2.2 如果是以.py结尾,那么就认为是动态资源的请求
header = 'HTTP/200 OK\r\n'
header += '\r\n'
body = mini_frame.application(file_name)
response = header + str(body) # body空值会报错
# 发送response给浏览器
new_socket.send(response.encode('utf-8'))