百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 热门文章 > 正文

Python mini web框架

bigegpt 2024-08-31 17:01 6 浏览

mini web框架-1-文件结构

文件结构

├── dynamic ---存放py模块
│ └── my_web.py
├── templates ---存放模板文件
│ ├── center.html
│ ├── index.html
│ ├── location.html
│ └── update.html
├── static ---存放静态的资源文件
│ ├── css
│ │ ├── bootstrap.min.css
│ │ ├── main.css
│ │ └── swiper.min.css
│ └── js
│ ├── a.js
│ ├── bootstrap.min.js
│ ├── jquery-1.12.4.js
│ ├── jquery-1.12.4.min.js
│ ├── jquery.animate-colors.js
│ ├── jquery.animate-colors-min.js
│ ├── jquery.cookie.js
│ ├── jquery-ui.min.js
│ ├── server.js
│ ├── swiper.jquery.min.js
│ ├── swiper.min.js
│ └── zepto.min.js
└── web_server.py ---mini web服务器

my_web.py

import time
def application(environ, start_response):
 status = '200 OK'
 response_headers = [('Content-Type', 'text/html')]
 start_response(status, response_headers)
 return str(environ) + '==Hello world from a simple WSGI application!--->%s\n' % time.ctime()

web_server.py

import select
import time
import socket
import sys
import re
import multiprocessing
class WSGIServer(object):
 """定义一个WSGI服务器的类"""
 def __init__(self, port, documents_root, app):
 # 1. 创建套接字
 self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 # 2. 绑定本地信息
 self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
 self.server_socket.bind(("", port))
 # 3. 变为监听套接字
 self.server_socket.listen(128)
 # 设定资源文件的路径
 self.documents_root = documents_root
 # 设定web框架可以调用的函数(对象)
 self.app = app
 def run_forever(self):
 """运行服务器"""
 # 等待对方链接
 while True:
 new_socket, new_addr = self.server_socket.accept()
 # 创建一个新的进程来完成这个客户端的请求任务
 new_socket.settimeout(3) # 3s
 new_process = multiprocessing.Process(target=self.deal_with_request, args=(new_socket,))
 new_process.start()
 new_socket.close()
 def deal_with_request(self, client_socket):
 """以长链接的方式,为这个浏览器服务器"""
 while True:
 try:
 request = client_socket.recv(1024).decode("utf-8")
 except Exception as ret:
 print("========>", ret)
 client_socket.close()
 return
 # 判断浏览器是否关闭
 if not request:
 client_socket.close()
 return
 request_lines = request.splitlines()
 for i, line in enumerate(request_lines):
 print(i, line)
 # 提取请求的文件(index.html)
 # GET /a/b/c/d/e/index.html HTTP/1.1
 ret = re.match(r"([^/]*)([^ ]+)", request_lines[0])
 if ret:
 print("正则提取数据:", ret.group(1))
 print("正则提取数据:", ret.group(2))
 file_name = ret.group(2)
 if file_name == "/":
 file_name = "/index.html"
 # 如果不是以py结尾的文件,认为是普通的文件
 if not file_name.endswith(".py"):
 # 读取文件数据
 try:
 f = open(self.documents_root+file_name, "rb")
 except:
 response_body = "file not found, 请输入正确的url"
 response_header = "HTTP/1.1 404 not found\r\n"
 response_header += "Content-Type: text/html; charset=utf-8\r\n"
 response_header += "Content-Length: %d\r\n" % (len(response_body))
 response_header += "\r\n"
 response = response_header + response_body
 # 将header返回给浏览器
 client_socket.send(response.encode('utf-8'))
 else:
 content = f.read()
 f.close()
 response_body = content
 response_header = "HTTP/1.1 200 OK\r\n"
 response_header += "Content-Length: %d\r\n" % (len(response_body))
 response_header += "\r\n"
 # 将header返回给浏览器
 client_socket.send(response_header.encode('utf-8') + response_body)
 # 以.py结尾的文件,就认为是浏览需要动态的页面
 else:
 # 准备一个字典,里面存放需要传递给web框架的数据
 env = dict()
 # 存web返回的数据
 response_body = self.app(env, self.set_response_headers)
 # 合并header和body
 response_header = "HTTP/1.1 {status}\r\n".format(status=self.headers[0])
 response_header += "Content-Type: text/html; charset=utf-8\r\n"
 response_header += "Content-Length: %d\r\n" % len(response_body)
 for temp_head in self.headers[1]:
 response_header += "{0}:{1}\r\n".format(*temp_head)
 response = response_header + "\r\n"
 response += response_body
 client_socket.send(response.encode('utf-8'))
 def set_response_headers(self, status, headers):
 """这个方法,会在 web框架中被默认调用"""
 response_header_default = [
 ("Data", time.time()),
 ("Server", "ItCast-python mini web server")
 ]
 # 将状态码/相应头信息存储起来
 # [字符串, [xxxxx, xxx2]]
 self.headers = [status, response_header_default + headers]
# 设置静态资源访问的路径
g_static_document_root = "./static"
# 设置动态资源访问的路径
g_dynamic_document_root = "./dynamic"
def main():
 """控制web服务器整体"""
 # python3 xxxx.py 7890
 if len(sys.argv) == 3:
 # 获取web服务器的port
 port = sys.argv[1]
 if port.isdigit():
 port = int(port)
 # 获取web服务器需要动态资源时,访问的web框架名字
 web_frame_module_app_name = sys.argv[2]
 else:
 print("运行方式如: python3 xxx.py 7890 my_web_frame_name:application")
 return
 print("http服务器使用的port:%s" % port)
 # 将动态路径即存放py文件的路径,添加到path中,这样python就能够找到这个路径了
 sys.path.append(g_dynamic_document_root)
 ret = re.match(r"([^:]*):(.*)", web_frame_module_app_name)
 if ret:
 # 获取模块名
 web_frame_module_name = ret.group(1)
 # 获取可以调用web框架的应用名称
 app_name = ret.group(2)
 # 导入web框架的主模块
 web_frame_module = __import__(web_frame_module_name)
 # 获取那个可以直接调用的函数(对象)
 app = getattr(web_frame_module, app_name) 
 # print(app) # for test
 # 启动http服务器
 http_server = WSGIServer(port, g_static_document_root, app)
 # 运行http服务器
 http_server.run_forever()
if __name__ == "__main__":
 main()

mini web框架-2-显示页面

dynamic/my_web.py (更新)

import time
import os
template_root = "./templates"
def index(file_name):
 """返回index.py需要的页面内容"""
 # return "hahha" + os.getcwd() # for test 路径问题
 try:
 file_name = file_name.replace(".py", ".html")
 f = open(template_root + file_name)
 except Exception as ret:
 return "%s" % ret
 else:
 content = f.read()
 f.close()
 return content
def center(file_name):
 """返回center.py需要的页面内容"""
 # return "hahha" + os.getcwd() # for test 路径问题
 try:
 file_name = file_name.replace(".py", ".html")
 f = open(template_root + file_name)
 except Exception as ret:
 return "%s" % ret
 else:
 content = f.read()
 f.close()
 return content
def application(environ, start_response):
 status = '200 OK'
 response_headers = [('Content-Type', 'text/html')]
 start_response(status, response_headers)
 file_name = environ['PATH_INFO']
 if file_name == "/index.py":
 return index(file_name)
 elif file_name == "/center.py":
 return center(file_name)
 else:
 return str(environ) + '==Hello world from a simple WSGI application!--->%s\n' % time.ctime()

web_server.py (更新)

import select
import time
import socket
import sys
import re
import multiprocessing
class WSGIServer(object):
 """定义一个WSGI服务器的类"""
 def __init__(self, port, documents_root, app):
 # 1. 创建套接字
 self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 # 2. 绑定本地信息
 self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
 self.server_socket.bind(("", port))
 # 3. 变为监听套接字
 self.server_socket.listen(128)
 # 设定资源文件的路径
 self.documents_root = documents_root
 # 设定web框架可以调用的函数(对象)
 self.app = app
 def run_forever(self):
 """运行服务器"""
 # 等待对方链接
 while True:
 new_socket, new_addr = self.server_socket.accept()
 # 创建一个新的进程来完成这个客户端的请求任务
 new_socket.settimeout(3) # 3s
 new_process = multiprocessing.Process(target=self.deal_with_request, args=(new_socket,))
 new_process.start()
 new_socket.close()
 def deal_with_request(self, client_socket):
 """以长链接的方式,为这个浏览器服务器"""
 while True:
 try:
 request = client_socket.recv(1024).decode("utf-8")
 except Exception as ret:
 print("========>", ret)
 client_socket.close()
 return
 # 判断浏览器是否关闭
 if not request:
 client_socket.close()
 return
 request_lines = request.splitlines()
 for i, line in enumerate(request_lines):
 print(i, line)
 # 提取请求的文件(index.html)
 # GET /a/b/c/d/e/index.html HTTP/1.1
 ret = re.match(r"([^/]*)([^ ]+)", request_lines[0])
 if ret:
 print("正则提取数据:", ret.group(1))
 print("正则提取数据:", ret.group(2))
 file_name = ret.group(2)
 if file_name == "/":
 file_name = "/index.html"
 # 如果不是以py结尾的文件,认为是普通的文件
 if not file_name.endswith(".py"):
 # 读取文件数据
 try:
 print(self.documents_root+file_name)
 f = open(self.documents_root+file_name, "rb")
 except:
 response_body = "file not found, 请输入正确的url"
 response_header = "HTTP/1.1 404 not found\r\n"
 response_header += "Content-Type: text/html; charset=utf-8\r\n"
 response_header += "Content-Length: %d\r\n" % (len(response_body))
 response_header += "\r\n"
 response = response_header + response_body
 # 将header返回给浏览器
 client_socket.send(response.encode('utf-8'))
 else:
 content = f.read()
 f.close()
 response_body = content
 response_header = "HTTP/1.1 200 OK\r\n"
 response_header += "Content-Length: %d\r\n" % (len(response_body))
 response_header += "\r\n"
 # 将header返回给浏览器
 client_socket.send(response_header.encode('utf-8') + response_body)
 # 以.py结尾的文件,就认为是浏览需要动态的页面
 else:
 # 准备一个字典,里面存放需要传递给web框架的数据
 env = dict()
 # ----------更新---------
 env['PATH_INFO'] = file_name # 例如 index.py
 # 存web返回的数据
 response_body = self.app(env, self.set_response_headers)
 # 合并header和body
 response_header = "HTTP/1.1 {status}\r\n".format(status=self.headers[0])
 response_header += "Content-Type: text/html; charset=utf-8\r\n"
 response_header += "Content-Length: %d\r\n" % len(response_body.encode("utf-8"))
 for temp_head in self.headers[1]:
 response_header += "{0}:{1}\r\n".format(*temp_head)
 response = response_header + "\r\n"
 response += response_body
 client_socket.send(response.encode('utf-8'))
 def set_response_headers(self, status, headers):
 """这个方法,会在 web框架中被默认调用"""
 response_header_default = [
 ("Data", time.time()),
 ("Server", "ItCast-python mini web server")
 ]
 # 将状态码/相应头信息存储起来
 # [字符串, [xxxxx, xxx2]]
 self.headers = [status, response_header_default + headers]
# 设置静态资源访问的路径
g_static_document_root = "./static"
# 设置动态资源访问的路径
g_dynamic_document_root = "./dynamic"
def main():
 """控制web服务器整体"""
 # python3 xxxx.py 7890
 if len(sys.argv) == 3:
 # 获取web服务器的port
 port = sys.argv[1]
 if port.isdigit():
 port = int(port)
 # 获取web服务器需要动态资源时,访问的web框架名字
 web_frame_module_app_name = sys.argv[2]
 else:
 print("运行方式如: python3 xxx.py 7890 my_web_frame_name:app")
 return
 print("http服务器使用的port:%s" % port)
 # 将动态路径即存放py文件的路径,添加到path中,这样python就能够找到这个路径了
 sys.path.append(g_dynamic_document_root)
 ret = re.match(r"([^:]*):(.*)", web_frame_module_app_name)
 if ret:
 # 获取模块名
 web_frame_module_name = ret.group(1)
 # 获取可以调用web框架的应用名称
 app_name = ret.group(2)
 # 导入web框架的主模块
 web_frame_module = __import__(web_frame_module_name)
 # 获取那个可以直接调用的函数(对象)
 app = getattr(web_frame_module, app_name) 
 # print(app) # for test
 # 启动http服务器
 http_server = WSGIServer(port, g_static_document_root, app)
 # 运行http服务器
 http_server.run_forever()
if __name__ == "__main__":
 main()

浏览器打开看效果

mini web框架-3-替换模板

dynamic/my_web.py

import time
import os
import re
template_root = "./templates"
def index(file_name):
 """返回index.py需要的页面内容"""
 # return "hahha" + os.getcwd() # for test 路径问题
 try:
 file_name = file_name.replace(".py", ".html")
 f = open(template_root + file_name)
 except Exception as ret:
 return "%s" % ret
 else:
 content = f.read()
 f.close()
 # --------更新-------
 data_from_mysql = "数据还没有敬请期待...."
 content = re.sub(r"\{%content%\}", data_from_mysql, content)
 return content
def center(file_name):
 """返回center.py需要的页面内容"""
 # return "hahha" + os.getcwd() # for test 路径问题
 try:
 file_name = file_name.replace(".py", ".html")
 f = open(template_root + file_name)
 except Exception as ret:
 return "%s" % ret
 else:
 content = f.read()
 f.close()
 # --------更新-------
 data_from_mysql = "暂时没有数据,,,,~~~~(>_<)~~~~ "
 content = re.sub(r"\{%content%\}", data_from_mysql, content)
 return content
def application(environ, start_response):
 status = '200 OK'
 response_headers = [('Content-Type', 'text/html')]
 start_response(status, response_headers)
 file_name = environ['PATH_INFO']
 if file_name == "/index.py":
 return index(file_name)
 elif file_name == "/center.py":
 return center(file_name)
 else:
 return str(environ) + '==Hello world from a simple WSGI application!--->%s\n' % time.ctime()

浏览器打开看效果

相关推荐

Java 泛型大揭秘:类型参数、通配符与最佳实践

引言在编程世界中,代码的可重用性和可维护性是至关重要的。为了实现这些目标,Java5引入了一种名为泛型(Generics)的强大功能。本文将详细介绍Java泛型的概念、优势和局限性,以及如何在...

K8s 的标签与选择器:流畅运维的秘诀

在Kubernetes的世界里,**标签(Label)和选择器(Selector)**并不是最炫酷的技术,但却是贯穿整个集群管理与运维流程的核心机制。正是它们让复杂的资源调度、查询、自动化运维变得...

哈希Hash算法:原理、应用(哈希算法 知乎)

原作者:Linux教程,原文地址:「链接」什么是哈希算法?哈希算法(HashAlgorithm),又称为散列算法或杂凑算法,是一种将任意长度的数据输入转换为固定长度输出值的数学函数。其输出结果通常被...

C#学习:基于LLM的简历评估程序(c# 简历)

前言在pocketflow的例子中看到了一个基于LLM的简历评估程序的例子,感觉还挺好玩的,为了练习一下C#,我最近使用C#重写了一个。准备不同的简历:image-20250528183949844查...

55顺位,砍41+14+3!季后赛也成得分王,难道他也是一名球星?

雷霆队最不可思议的新星:一个55号秀的疯狂逆袭!你是不是也觉得NBA最底层的55号秀,就只能当饮水机管理员?今年的55号秀阿龙·威金斯恐怕要打破你的认知了!常规赛阶段,这位二轮秀就像开了窍的天才,直接...

5分钟读懂C#字典对象(c# 字典获取值)

什么是字典对象在C#中,使用Dictionary类来管理由键值对组成的集合,这类集合被称为字典。字典最大的特点就是能够根据键来快速查找集合中的值,其键的定义不能重复,具有唯一性,相当于数组索引值,字典...

c#窗体传值(c# 跨窗体传递数据)

在WinForm编程中我们经常需要进行俩个窗体间的传值。下面我给出了两种方法,来实现传值一、在输入数据的界面中定义一个属性,供接受数据的窗体使用1、子窗体usingSystem;usingSyst...

C#入门篇章—委托(c#委托的理解)

C#委托1.委托的定义和使用委托的作用:如果要把方法作为函数来进行传递的话,就要用到委托。委托是一个类型,这个类型可以赋值一个方法的引用。C#的委托通过delegate关键字来声明。声明委托的...

C#.NET in、out、ref详解(c#.net framework)

简介在C#中,in、ref和out是用于修改方法参数传递方式的关键字,它们决定了参数是按值传递还是按引用传递,以及参数是否必须在传递前初始化。基本语义对比修饰符传递方式可读写性必须初始化调用...

C#广义表(广义表headtail)

在C#中,广义表(GeneralizedList)是一种特殊的数据结构,它是线性表的推广。广义表可以包含单个元素(称为原子),也可以包含另一个广义表(称为子表)。以下是一个简单的C#广义表示例代...

「C#.NET 拾遗补漏」04:你必须知道的反射

阅读本文大概需要3分钟。通常,反射用于动态获取对象的类型、属性和方法等信息。今天带你玩转反射,来汇总一下反射的各种常见操作,捡漏看看有没有你不知道的。获取类型的成员Type类的GetMembe...

C#启动外部程序的问题(c#怎么启动)

IT&OT的深度融合是智能制造的基石。本公众号将聚焦于PLC编程与上位机开发。除理论知识外,也会结合我们团队在开发过程中遇到的具体问题介绍一些项目经验。在使用C#开发上位机时,有时会需要启动外部的一些...

全网最狠C#面试拷问:这20道题没答出来,别说你懂.NET!

在竞争激烈的C#开发岗位求职过程中,面试是必经的一道关卡。而一场高质量的面试,不仅能筛选出真正掌握C#和.NET技术精髓的人才,也能让求职者对自身技术水平有更清晰的认知。今天,就为大家精心准备了20道...

C#匿名方法(c#匿名方法与匿名类)

C#中的匿名方法是一种没有名称只有主体的方法,它提供了一种传递代码块作为委托参数的技术。以下是关于C#匿名方法的一些重要特点和用法:特点省略参数列表:使用匿名方法可省略参数列表,这意味着匿名方法...

C# Windows窗体(.Net Framework)知识总结

Windows窗体可大致分为Form窗体和MDI窗体,Form窗体没什么好细说的,知识点总结都在思维导图里面了,下文将围绕MDI窗体来讲述。MDI(MultipleDocumentInterfac...