翼度科技»论坛 编程开发 python 查看内容

Python实现搭建-简单服务器教程

5

主题

5

帖子

15

积分

新手上路

Rank: 1

积分
15
Python动态服务器网页(需要使用WSGI接口),基本实现步骤如下:
1.等待客户端的链接,服务器会收到一个http协议的请求数据报
2.利用正则表达式对这个请求数据报进行解析(请求方式、提取出文件的环境)
3.提取出文件的环境之后,利用截断取片的方法将文件名转化为模块名称
4.使用m = __import__(),就可以得到返回值为m的模块
5.创建一个env字典:其中包含的是请求方式及文件环境等各种的键值对
6.创建一个新的动态脚本,其中定义了application这个函数,必须包含env和start_response的参数(也是服务器里的调用方法)
7.在这个动态脚本中定义状态码status和响应头headers(注意是字典形式,如Content-Type)
8.然后再调用start_response(status,headers),但是要注意,这个函数在服务器被定义
9.在动态脚本中编写动态执行程序
10.m.appliction的返回值就是回应数据包的body,它的数据头在start_response被整合
11.将数据头与数据body拼接起来,然后发送给客户端,就可显示动态网页
MyWebServer
  1. import socket
  2. import re
  3. import sys
  4. from multiprocessing import Process
  5. from MyWebFramework import Application
  6. # 设置静态文件根目录
  7. HTML_ROOT_DIR = "./html"
  8. WSGI_PYTHON_DIR = "./wsgipython"
  9. class HTTPServer(object):
  10.     """"""
  11.     def __init__(self, application):
  12.         """构造函数, application指的是框架的app"""
  13.         self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  14.         self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  15.         self.app = application
  16.     def start(self):
  17.         self.server_socket.listen(128)
  18.         while True:
  19.             client_socket, client_address = self.server_socket.accept()
  20.             #print("[%s,%s]用户连接上了" % (client_address[0],client_address[1]))
  21.             print("[%s, %s]用户连接上了" % client_address)
  22.             handle_client_process = Process(target=self.handle_client, args=(client_socket,))
  23.             handle_client_process.start()
  24.             client_socket.close()
  25.     def start_response(self, status, headers):
  26.         """
  27.          status = "200 OK"
  28.     headers = [
  29.         ("Content-Type", "text/plain")
  30.     ]
  31.     star
  32.         """
  33.         response_headers = "HTTP/1.1 " + status + "\r\n"
  34.         for header in headers:
  35.             response_headers += "%s: %s\r\n" % header
  36.         self.response_headers = response_headers
  37.     def handle_client(self, client_socket):
  38.         """处理客户端请求"""
  39.         # 获取客户端请求数据
  40.         request_data = client_socket.recv(1024)
  41.         print("request data:", request_data)
  42.         request_lines = request_data.splitlines()
  43.         for line in request_lines:
  44.             print(line)
  45.         # 解析请求报文
  46.         # 'GET / HTTP/1.1'
  47.         request_start_line = request_lines[0]
  48.         # 提取用户请求的文件名
  49.         print("*" * 10)
  50.         print(request_start_line.decode("utf-8"))
  51.         file_name = re.match(r"\w+ +(/[^ ]*) ", request_start_line.decode("utf-8")).group(1)
  52.         method = re.match(r"(\w+) +/[^ ]* ", request_start_line.decode("utf-8")).group(1)
  53.         env = {
  54.             "PATH_INFO": file_name,
  55.             "METHOD": method
  56.         }
  57.         response_body = self.app(env, self.start_response)
  58.         response = self.response_headers + "\r\n" + response_body
  59.         # 向客户端返回响应数据
  60.         client_socket.send(bytes(response, "utf-8"))
  61.         # 关闭客户端连接
  62.         client_socket.close()
  63.     def bind(self, port):
  64.         self.server_socket.bind(("", port))
  65. def main():
  66.     sys.path.insert(1, WSGI_PYTHON_DIR)
  67.     if len(sys.argv) < 2:
  68.         sys.exit("python MyWebServer.py Module:app")
  69.     # python MyWebServer.py  MyWebFrameWork:app
  70.     module_name, app_name = sys.argv[1].split(":")
  71.     # module_name = "MyWebFrameWork"
  72.     # app_name = "app"
  73.     m = __import__(module_name)
  74.     app = getattr(m, app_name)
  75.     http_server = HTTPServer(app)
  76.     # http_server.set_port
  77.     http_server.bind(8000)
  78.     http_server.start()
  79. if __name__ == "__main__":
  80.     main()
复制代码
MyWebFrameWork
  1. import time
  2. # from MyWebServer import HTTPServer
  3. # 设置静态文件根目录
  4. HTML_ROOT_DIR = "./html"
  5. class Application(object):
  6.     """框架的核心部分,也就是框架的主题程序,框架是通用的"""
  7.     def __init__(self, urls):
  8.         # 设置路由信息
  9.         self.urls = urls
  10.     def __call__(self, env, start_response):
  11.         path = env.get("PATH_INFO", "/")
  12.         # /static/index.html
  13.         if path.startswith("/static"):
  14.             # 要访问静态文件
  15.             file_name = path[7:]
  16.             # 打开文件,读取内容
  17.             try:
  18.                 file = open(HTML_ROOT_DIR + file_name, "rb")
  19.             except IOError:
  20.                 # 代表未找到路由信息,404错误
  21.                 status = "404 Not Found"
  22.                 headers = []
  23.                 start_response(status, headers)
  24.                 return "not found"
  25.             else:
  26.                 file_data = file.read()
  27.                 file.close()
  28.                 status = "200 OK"
  29.                 headers = []
  30.                 start_response(status, headers)
  31.                 return file_data.decode("utf-8")
  32.         for url, handler in self.urls:
  33.             #("/ctime", show_ctime)
  34.             if path == url:
  35.                 return handler(env, start_response)
  36.         # 代表未找到路由信息,404错误
  37.         status = "404 Not Found"
  38.         headers = []
  39.         start_response(status, headers)
  40.         return "not found"
  41. def show_ctime(env, start_response):
  42.     status = "200 OK"
  43.     headers = [
  44.         ("Content-Type", "text/plain")
  45.     ]
  46.     start_response(status, headers)
  47.     return time.ctime()
  48. def say_hello(env, start_response):
  49.     status = "200 OK"
  50.     headers = [
  51.         ("Content-Type", "text/plain")
  52.     ]
  53.     start_response(status, headers)
  54.     return "hello itcast"
  55. def say_haha(env, start_response):
  56.     status = "200 OK"
  57.     headers = [
  58.         ("Content-Type", "text/plain")
  59.     ]
  60.     start_response(status, headers)
  61.     return "hello haha"
  62. urls = [
  63.             ("/", show_ctime),
  64.             ("/ctime", show_ctime),
  65.             ("/sayhello", say_hello),
  66.             ("/sayhaha", say_haha),
  67.         ]
  68. app = Application(urls)
  69. # if __name__ == "__main__":
  70. #     urls = [
  71. #             ("/", show_ctime),
  72. #             ("/ctime", show_ctime),
  73. #             ("/sayhello", say_hello),
  74. #             ("/sayhaha", say_haha),
  75. #         ]
  76. #     app = Application(urls)
  77. #     http_server = HTTPServer(app)
  78. #     http_server.bind(8000)
  79. #     http_server.start()
复制代码
来源:https://www.cnblogs.com/djdjdj123/p/17329903.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具