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()




import socket

import re

import multiprocessing

import time

import mini_frame026

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();

# if file_name == "/login.py"

# body = mini_frame026.login()

# elif file_name == "/register.py":

# body = mini_frame026.register()

body = mini_frame026.application(file_name)

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()



闭包

由于闭包引用了外部函数的局部变量,则外部函数的局部变量没有及时释放,消耗内存

x = 300

def test1():

    x=200

    def test2():

        # global x

        nonlocal x

        print('---1---x=%d'%x)

        x=100

        print('---2---x=%s'%x)

    return test2

t1 = test1()

t1()

装饰器

装饰器就是用于拓展函数功能的一种函数,它的特殊之处,在于它的返回值也是一个函数,使用装饰器的好处就是,在不用更改原函数代码的前提下,给函数增加新的功能

def outside1(test):

    print('执行了装饰器外部函数1')

    def inside(*args,**kwargs):

        print('welcome1')

        return test(*args,**kwargs)

    return inside

def outside2(test):

    print('执行了装饰器外部函数2')

    def inside(*args,**kwargs):

        print('welcome2')

        return test(*args,**kwargs)

    return inside

@outside1

@outside2

def func(*args,**kwargs):

    print(kwargs)

    # print(*args,**kwargs)

    # print('hello world')

#

# a = outside1(func)

# a()

func(a=1,b=2)

带参数的装饰器

def set_level(level_num):

    def set_func(func):

        def call_func(*args,**kwargs):

            if level_num == 1:

                print('---权限级别1,验证---')

            elif level_num == 2:

                print('---权限级别2,验证---')

            elif level_num == 10:

                print('---权限级别10,验证---')

            return func()

        return call_func

    return set_func

@set_level(10)

def test1():

    print('---test1---')

    return 'ok'

@set_level(2)

def test2():

    print('---test2---')

    return 'ok'

test1()

test2()

你可能感兴趣的:(web服务器集成解析动态请求的功能与服务器和逻辑处理代码分开,闭包,装饰器,带参数的装饰器)