python-实现动态web服务器
# encoding=utf-8
import socket
from multiprocessing import Process
import re
import sys # 设置静态文件根目录
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 = application def 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" % header self.response_headers = response_headers def handle_socket(self, client_socket):
"""处理客户端请求"""
# 获取客户端请求数据
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) # 解析请求报文
# 'GET / HTTP/1.1'
request_start_line = request_lines[0]
print('&' * 20)
print(type(request_start_line))
# 提取用户请求的文件名
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)
# 将路由的分发交给框架去做 ====================================================
# # "/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'
#
# # 打开文件,读取内容
# 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()
#
# # 构造响应数据
# 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 # 向客户端返回响应数据
client_socket.send(bytes(response, 'utf-8')) # 关闭客户端连接
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:app
module_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_port
http_server.bind(9000)
http_server.start() if __name__ == '__main__':
main()
框架的实现
MyWebFrameWork_v2.py
# coding:utf-8 import time # 设置静态文件根目录
HTML_ROOT_DIR = "./html" class Application(object):
"""框架的核心部分,也就是框架的主题程序,框架是通用的"""
def __init__(self, urls):
# 设置路由信息
self.urls = urls def __call__(self, env, start_response):
path = env.get("PATH_INFO", "/")
# /static/index.html
if path.startswith("/static"):
# 要访问静态文件
file_name = path[7:]
# 打开文件,读取内容
try:
file = open(HTML_ROOT_DIR + file_name, "rb")
except IOError:
# 代表未找到路由信息,404错误
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错误
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)
运行上述代码需要pycharm中配置
服务器程序--Edit Configurations....

python-实现动态web服务器的更多相关文章
- python网络-动态Web服务器案例(30)
一.浏览器请求HTML页面的过程 了解了HTTP协议和HTML文档,其实就明白了一个Web应用的本质就是: 浏览器发送一个HTTP请求: 服务器收到请求,生成一个HTML文档: 服务器把HTML文档作 ...
- python 启动简单web服务器
有时我们在开发web静态页面时,需要一个web服务器来测试. 这时可以利用python提供的web服务器来实现. 1.在命令行下进入某个目录 2.在该目录下运行命令: python -m Simple ...
- 利用Python实现对Web服务器的目录探测
今天是一篇提升技能的干货分享,操作性较强,适用于中级水平的小伙伴,文章阅读用时约3分钟. PART 1/Python Python是一种解释型.面向对象.动态数据类型的高级程序设计语言. Python ...
- 利用 python 实现对web服务器的目录探测
一.pythonPython是一种解释型.面向对象.动态数据类型的高级程序设计语言.python 是一门简单易学的语言,并且功能强大也很灵活,在渗透测试中的应用广泛,让我们一起打造属于自己的渗透测试工 ...
- 基于python实现简单web服务器
做web开发的你,真的熟悉web服务器处理机制吗? 分析请求数据 下面是一段原始的请求数据: b'GET / HTTP/1.1\r\nHost: 127.0.0.1:8000\r\nConnectio ...
- 用python快速搭建WEB服务器
cmd下进入你要搞WEB项目的目录 输入↓方代码 python -m SimpleHTTPServer 端口号# 默认是8000 这样就启动了一个简单的WEB服务器
- python下的web服务器模块
python下的web服务模块有三种: BaseHTTPServer: 提供基本的Web服务和处理器类,分别是HTTPServer和BaseHTTPRequestHandler SimpleHTTPS ...
- <5>Python的uwsgi web服务器
一.是什么? uWSGI是web服务器,用来部署线上web应用到生产环境.uWSGI实现了WSGI协议.uwsgi协议.http协议.WSGI(Web Server Gateway Interface ...
- python网络-静态Web服务器案例(29)
一.静态Web服务器案例代码static_web_server.py # coding:utf-8 # 导入socket模块 import socket # 导入正则表达式模块 import re # ...
- Python实现简易Web服务器
1.请自行了解HTTP协议 http://www.cnblogs.com/reboot51/p/8358129.html(点击跳转) 2.创建Socket服务,监听指定IP和端口 3.以阻塞方式等待 ...
随机推荐
- 【C++复习】第九章 模板与群体数据(2)
学习重点:容器类型内部的实现机制,顺便复习前面各章内容.容器类型的具体实现不需要特别关注(目前不需要会裸手写这么一个容器类型) 1.群体/线性群体 群体的概念 群体是指由多个数据元素组成的集合体.群体 ...
- QSlider CSS样式
QSlider::groove:horizontal{ border:0px; height:15px; background:#deffe5; } QSlider::sub-page:horizon ...
- ubuntu 20.04 基于kubeadm部署kubernetes 1.22.4集群—报错解决
一.添加node节点,报错1 注:可以提前在各node节点上修改好(无报错无需执行此项) yang@node2:~$ sudo kubeadm join 192.168.1.101:6443 --to ...
- 转L:[JAVA基础] 成员变量和局部变量(一看就懂的总结归纳篇)
[JAVA基础] 成员变量和局部变量(一看就懂的总结归纳篇) JVM--Java虚拟机详解
- Notepad++轻量级java环境
2020-07-11 summary: Notepad++搭建轻量级java环境 notepad++搭建轻量级Java 原因:不想用eclipse 一.本机环境 Windows10 64位 已安装No ...
- shell_Day01
1.判断/etc/inittab文件是否大于100行,如果大于,则显示"/etc/inittab is a big file."否者显示"/etc/inittab is ...
- A - Add Odd or Subtract Even
A - Add Odd or Subtract Even 思路:其实认真观察就能发现,这个与输入的书有关系,且答案为0,1,2.先看相同,不用加减,为0,再看前小后大,因为加奇数减偶数,如果,相差奇数 ...
- iOS开发--APP性能检测方案汇总
1 . CPU 占用率 CPU作为手机的中央处理器,可以说是手机最关键的组成部分,所有应用程序都需要它来调度运行,资源有限.所以当我们的APP因设计不当,使 CPU 持续以高负载运行,将会出现APP卡 ...
- WSL2与ensp的40故障
在使用ensp做radius认证的时候看到了Linux平台的freeradius认证服务器,于是使用了Windows平台的sub system: WSL2,按照网上的教程安装,并且安装了docker ...
- 2020年第11届蓝桥杯C/C++B组 第一轮省赛
# JJU-干干 试题 A: 跑步训练 代码: #include <stdio.h> #include <stdlib.h> /* run this program using ...