python - 使用 socketserver 处理 http 协议
问题描述
使用 socketserver 处理 http 协议
我正在构建一个 Web 服务器(...),旨在解释 Python 语言(就像 apache 对 php 所做的那样)。我使用python的socketserver模块通过TCP协议在传输层建立连接(客户端x服务器)。现在我需要捕获请求头数据并向客户端(浏览器)发送一个 http 响应,我该怎么做呢?下面是处理的代码和结果:
文件:httptcpipv4.py
# Module Name : socketserver -> https://docs.python.org/3/library/socketserver.html#module-socketserver
from socketserver import BaseRequestHandler, ThreadingTCPServer
# Transport Layer Protocol : TCP
# This is the superclass of all request handler objects. It defines the interface, given below.
class HTTPTCPIPv4(BaseRequestHandler):
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).decode()
print(self.data)
if __name__ == "__main__":
HOST, PORT = "", 8080
# Create the asynchronous server, binding to localhost on port 8080
with ThreadingTCPServer((HOST, PORT), HTTPTCPIPv4) as server:
print("Server : Action v0.0.1, running address http://127.0.0.1:8080,")
print("cancel program with Ctrl-C")
server.serve_forever()
输出 :
GET / HTTP/1.1
Host: 127.0.0.1:8080
Connection: keep-alive
sec-ch-ua: " Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"
sec-ch-ua-mobile: ?0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Purpose: prefetch
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br
Accept-Language: pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7
解决方案
推荐阅读
- python - AppEngine 警告 - OpenBLAS 警告 - 无法确定此系统上的 L2 缓存大小
- javascript - 对组件的@Input 进行严格的类型检查
- c# - 回调未在 Unity 插件内的 C# 脚本中触发
- css - Designinig SASS 我想要 Box 布局但无法得到它
- sql - Postgresql 选择最后一组的第一项
- angular - 条带 oAuth 令牌 URL 被 CORS 阻止
- assembly - 穿过带有 .word 的标签的臂组件
- ios - 如何让 Swift 在 seguing 后记住 UIImage 颜色
- reactjs - 在 React 中访问容器状态的更好方法是什么
- python - plotly dash:如何在不同的刻度中绘制 y 轴?