python-实现动态web服务器
生活随笔
收集整理的這篇文章主要介紹了
python-实现动态web服务器
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
# encoding=utf-8 import socket from multiprocessing import Process import re import sys# 設(shè)置靜態(tài)文件根目錄 HTML_ROOT_DIR = './html'WSGI_PYTHON_DIR = './wsgipython'class HTTPServer(object):def __init__(self, application):self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)self.app = applicationdef start(self):self.server_socket.listen(128)while True:client_socket, client_address = self.server_socket.accept()# print("[%s, %s]用戶連接上了" % (client_address[0], client_address[1]))print("[%s, %s]用戶連接上了" % client_address)handle_client_process = Process(target=self.handle_socket, args=(client_socket,))handle_client_process.start()client_socket.close()def start_response(self, status, headers):"""status="200 ok"headers = [('Content-Type', 'text/plain')]:param status::param headers::return:"""response_headers = "HTTP1.1 " + status + "\r\n"for header in headers:response_headers += "%s: %s\r\n" % headerself.response_headers = response_headersdef handle_socket(self, client_socket):"""處理客戶端請(qǐng)求"""# 獲取客戶端請(qǐng)求數(shù)據(jù)request_data = client_socket.recv(1024)print("request data: ", request_data)request_lines = request_data.splitlines()for request_line in request_lines:print(request_line)# 解析請(qǐng)求報(bào)文# 'GET / HTTP/1.1'request_start_line = request_lines[0]print('&' * 20)print(type(request_start_line))# 提取用戶請(qǐng)求的文件名print('*' * 10)print(request_start_line.decode('utf-8'))file_name = re.match(r"\w+ +(/[^ ]*) ", request_start_line.decode('utf-8')).group(1)method = re.match(r"(\w+) +/[^ ]* ", request_start_line.decode('utf-8')).group(1)print(file_name)
# 將路由的分發(fā)交給框架去做 ====================================================# # "/ctime.py"# # "/sayhello.py"# if file_name.endswith('.py'):# a = file_name[1:-3]# try:# m = __import__(file_name[1:-3])# except Exception:# self.response_headers = "HTTP/1/1 404 Not Found\r\n"# response_body = 'not found'# else:# env = {# "PATH_INFO": file_name,# 'METHOD': method# }# # response_body = m.application(env, self.start_response)# # response = self.response_headers + '\r\n' + response_body# # else:# if '/' == file_name:# file_name = '/index.html'# # # 打開(kāi)文件,讀取內(nèi)容# try:# file = open(HTML_ROOT_DIR + file_name, "rb")# except IOError:# response_start_line = 'HTTP/1.1 404 Not Found\r\n'# response_headers = 'Server: Myserver\r\n'# response_body = 'The file is not found!'# else:# file_data = file.read()# file.close()# # # 構(gòu)造響應(yīng)數(shù)據(jù)# response_start_line = 'HTTP/1.1 200 OK\r\n'# response_headers = 'Server: Myserver\r\n'# response_body = file_data.decode('utf-8')# print('??' * 20)# print(type(response_body))# # response = response_start_line + response_headers + '\r\n' + response_body# print('response data:', response) env = {"PATH_INFO": file_name,'METHOD': method}response_body = self.app(env, self.start_response)response = self.response_headers + '\r\n' + response_body# 向客戶端返回響應(yīng)數(shù)據(jù)client_socket.send(bytes(response, 'utf-8'))# 關(guān)閉客戶端連接 client_socket.close()def bind(self, port):self.server_socket.bind(("", port))def main():sys.path.insert(1, WSGI_PYTHON_DIR)if len(sys.argv) < 2:sys.exit("python MyWebServer_v1.py Module:app")# python MyWebServer_v1.py MyWebFrameWork:appmodule_name, app_name = sys.argv[1].split(":")# module_name = "MyWebFrameWork"# app_name = "app"m = __import__(module_name)app = getattr(m, app_name)http_server = HTTPServer(app)# http_server.set_porthttp_server.bind(9000)http_server.start()if __name__ == '__main__':main()
?
?
框架的實(shí)現(xiàn)
MyWebFrameWork_v2.py
# coding:utf-8import time# 設(shè)置靜態(tài)文件根目錄 HTML_ROOT_DIR = "./html"class Application(object):"""框架的核心部分,也就是框架的主題程序,框架是通用的"""def __init__(self, urls):# 設(shè)置路由信息self.urls = urlsdef __call__(self, env, start_response):path = env.get("PATH_INFO", "/")# /static/index.htmlif path.startswith("/static"):# 要訪問(wèn)靜態(tài)文件file_name = path[7:]# 打開(kāi)文件,讀取內(nèi)容try:file = open(HTML_ROOT_DIR + file_name, "rb")except IOError:# 代表未找到路由信息,404錯(cuò)誤status = "404 Not Found"headers = []start_response(status, headers)return "not found"else:file_data = file.read()file.close()status = "200 OK"headers = []start_response(status, headers)return file_data.decode("utf-8")for url, handler in self.urls:#("/ctime", show_ctime)if path == url:return handler(env, start_response)# 代表未找到路由信息,404錯(cuò)誤status = "404 Not Found"headers = []start_response(status, headers)return "not found"def show_ctime(env, start_response):status = "200 OK"headers = [("Content-Type", "text/plain")]start_response(status, headers)return time.ctime()def say_hello(env, start_response):status = "200 OK"headers = [("Content-Type", "text/plain")]start_response(status, headers)return "hello frawework"def say_haha(env, start_response):status = "200 OK"headers = [("Content-Type", "text/plain")]start_response(status, headers)return "hello haha"urls = [("/", show_ctime),("/ctime", show_ctime),("/sayhello", say_hello),("/sayhaha", say_haha),] app = Application(urls)?
運(yùn)行上述代碼需要pycharm中配置
服務(wù)器程序--Edit Configurations....
?
轉(zhuǎn)載于:https://www.cnblogs.com/wgDream/p/7536904.html
總結(jié)
以上是生活随笔為你收集整理的python-实现动态web服务器的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 使用BootStrap框架设置全局CSS
- 下一篇: 梦到女朋友买车是什么意思