学习Python的日子 Python高级(11)

Python高级
回顾
tcp
udp


---》应用层协议: http
http
https


request:请求  客户端


response: 响应  服务器


web服务器:
1.接收客户端的请求
请求行 GET /test.html    POST | GET
请求头 key:value
请求体
GET  --->url字符串   http://192.168.28.74:8080/mysite?username=admin&pwd=1234
POST --->请求体


2.响应:
响应行  ---》  HTTP/1.1 200 OK
响应头  ---》server:。。。。。  Content-Type: text/html  Content-Length:4567
响应体  ---》html标签


web服务器:
1.固定内容   response= 响应行+响应头+响应体   ---> sock.send(response.encode("utf-8"))
2.静态文件   http://192.168.28.74:8080/mysite/aa.html
file_name=/aa.html
fr=open("."+file_name,"rb")   ---->fr.read()  ---->response_body
3.动态: xxx.py


file_name=xxxx.py
if file_name.endswith("py"):
动态   ---》
__import__(xxxx)   +   sys.path.insert(1,"....")
else:
静态


WSGI:
MyWebFramework
import time
# from python0523.MyServer import HttpServer




class Application(object):
def __init__(self, urls):
self.urls = urls


def __call__(self, env, start_response):  # 为什么必须是可调用
# env --->dict  环境信息
# start_response  ---》回调函数
path = env.get("PATH_INFO")  # /ctime    /static/hello.html
print("application ---->path:", path)
if path.startswith("/static"):
file_name = path[7:]
flag=False
try:
if file_name.endswith("html"):
fr = open("./html" + file_name, "rb")
flag=True
elif file_name.endswith("png"):
fr = open("./images" + file_name, "rb")


except:
# 处理异常
status = "404 NOT FOUND"


headers = [
("Server", "ABC server"), ("Content-Type", "text/plain;charset=utf-8")
]


start_response(status, headers)


return "文件没有找到!"
else:
data = fr.read()
fr.close()


# 处理异常
status = "200 OK"
headers = [
("Server", "ABC server"), ("Content-Type", "text/html;charset=utf-8")
]
if flag:
start_response(status, headers)
return data.decode("utf-8")
else:
headers=[("Server", "ABC server"), ("Content-Type", "image/jpeg")]
start_response(status, headers)
return data


for url, func in self.urls:
# 进行判断
if path == url:
response_body = func(env, start_response)


return response_body


# 处理异常
status = "404 NOT FOUND"


headers = [
("Server", "ABC server"), ("Content-Type", "text/html;charset=utf-8")
]


start_response(status, headers)


return "文件没有找到!"




def say_hello(env, start_response):
status = "200 OK"
headers = [
("Server", "ABC server"), ("Content-Type", "text/html;charset=utf-8")
]
# Application 内部在返回前调用 start_response
start_response(status, headers)  # ---->header  响应头+响应行


return "hello world!"  # response_body




def get_time(env, start_response):
status = "200 OK"
headers = [
("Server", "ABC server"), ("Content-Type", "text/html;charset=utf-8")
]
# Application 内部在返回前调用 start_response
start_response(status, headers)  # ---->header  响应头+响应行
return time.ctime()




def print_A(env, start_response):
status = "200 OK"
headers = [
("Server", "ABC server"), ("Content-Type", "text/html;charset=utf-8")
]
# Application 内部在返回前调用 start_response
start_response(status, headers)  # ---->header  响应头+响应行
return "AAAAAAAAAAAAA"


urls = [
("/ctime", get_time),
("/sayhello", say_hello),
("/printA", print_A)
]


app=Application(urls)


if __name__ == "__main__":
pass


# # 创建 对象
# app = Application(urls)
#
# server = HttpServer(app)  # 创建server对象
# server.bind(8080)
# server.start()  # 等待客户端的连接


MyServer
from socket import *
from threading import Thread
import re
import sys
# from python0523.MyWebFramework02 import Application


class HttpServer:
def __init__(self, app):
self.app = app
self.server_socket = socket(AF_INET, SOCK_STREAM)
self.server_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)


def bind(self, port):
self.server_socket.bind(("", port))


def start(self):
self.server_socket.listen(5)


while True:
new_socket, new_addr = self.server_socket.accept()
Thread(target=self.handle_client, args=(new_socket,)).start()


def stop(self):
self.server_socket.close()


# 2.定义start_response
def start_response(self, status, headers):
response_line = "HTTP/1.1 " + status + "\r\n"
response_headers = response_line
for header in headers:
response_headers += "%s:%s" % header + "\r\n"
self.response_header = response_headers


def handle_client(self, new_socket):
request_data = new_socket.recv(1024)
msg = request_data.decode("utf-8")
list1 = msg.splitlines()  # GET /ctime.py
file_name = re.match(r"\w+ +(/[^ ]*)", list1[0]).group(1)  # /hello.html   /ctime.py   /static/hello.html
method = re.match(r"(\w+) +(/[^ ]*)", list1[0]).group(1)
# application接收由server转发的request,处理请求,并将处理结果返回给server
# 1. 环境信息
env = {
"PATH_INFO": file_name,
"METHOD": method
}
# 3. 调用app 得到response_body中返回值
response_body = self.app(env, self.start_response)


response = self.response_header + "\r\n" + response_body


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


new_socket.close()




if __name__ == "__main__":
sys.path.insert(1, "./wsgi")
# urls = [
# ("/ctime", get_time),
# ("/sayhello", say_hello),
# ("/printA", print_A)
# ]
argvs=sys.argv[1]
print(argvs)
module_name,app_name=argvs.split(":") # 1. MyWebFramework02:Application  2.MyWebFramework02:app
m=__import__(module_name)


app=getattr(m,app_name)
print(app)
#
# app = Application(urls)
server = HttpServer(app)  # 创建server对象
server.bind(8080)
server.start()  # 等待客户端的连接

猜你喜欢

转载自blog.csdn.net/qq_42240071/article/details/80455468