web服务器集成解析动态请求的功能

import socket

import re

import multiprocessing

import time

class WSGTServer(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、变为监听套接字(最大链接数128)

self.tcp_server_socket.listen(128)# 调用listen变为被动

def service_client(self,new_socket):

# 为这个客户端返回数据

# 1、接收浏览器发送过来的请求

# GET / HTTP/1.1

# ......

request = new_socket.recv(1024).decode("utf-8")

# print('<<<<<' * 20)

# print(request)

request_lines = request.splitlines()

print("")

print(">" * 20)

print(request_lines)

# GET /index.py HTTP/1.1

# get post put del

ret = re.match(r"[^/]+(/[^ ]*)", request_lines[0])# *:0个~~多个

file_name = ""

if ret:

file_name = ret.group(1)

print("*" * 50, file_name)

if file_name == '/':

file_name = '/丝芙兰.html'

# 2、返回HTTP格式的数据给浏览器

# 2.1 如果请求的资源不是以.py结尾,那么就认为是静态资源(html/css/js/png/jpg)

if not file_name.endswith(".py"):

try:

# f = open("../创维官方商场-权威官网 彩电领导者/charry.html", "rb")

f = open("../sephore" + 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()

f.close()

# 2.1准备发送给浏览器的Header

response = "HTTP/1.1 200 OK\r\n"

response += "\r\n"

# 2.2准备发送给浏览器的Body

# response += "

hahaha

"

# 将Response Heard 发送给浏览器

new_socket.send(response.encode("utf-8"))

# 将Response Body 发送给浏览器

new_socket.send(html_content)

else: # 2.2 如果是以.py结尾,就认为是动态资源的请求

header = "HTTP/1.1 200 OK\r\n"

header += "\r\n"

body = "hahaha %s" % time.ctime();

response = header + body

# 发送response给浏览器

new_socket.send(response.encode("utf-8"))

# 关闭客户端套接字

new_socket.close()

def run_forever(self):

while True:

# 4、等待新客户端的连接

new_socket, client_addr = self.tcp_server_socket.accept()

# 5、为这个客户端服务

# service_client(new_socket)

p = multiprocessing.Process(target=self.service_client, args=(new_socket,))

p.start()

new_socket.close()

# 6、关闭监听套接字

self.tcp_server_socket.close()

def main():

# 用来完成整体的控制,创建一个web服务器对象,调用run_forever方法运行

wsgi_server = WSGTServer()

wsgi_server.run_forever()

if __name__ == '__main__':

main()

你可能感兴趣的:(web服务器集成解析动态请求的功能)