requrst 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
requrst-0.5.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 shiroko
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
requrst-0.5.0/PKG-INFO ADDED
@@ -0,0 +1,34 @@
1
+ Metadata-Version: 2.4
2
+ Name: requrst
3
+ Version: 0.5.0
4
+ Summary: 纯Python Socket手写HTTP/HTTPS客户端,零第三方依赖,第二方自研请求库
5
+ Home-page:
6
+ Author:
7
+ Author-email:
8
+ License: MIT
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.6
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Dynamic: classifier
16
+ Dynamic: description
17
+ Dynamic: description-content-type
18
+ Dynamic: license
19
+ Dynamic: license-file
20
+ Dynamic: requires-python
21
+ Dynamic: summary
22
+
23
+ # pure-socket-http
24
+ 纯原生Socket手写HTTP/HTTPS协议栈,零依赖
25
+
26
+ 特性:
27
+ - 零第三方依赖
28
+ - 自动301/302重定向
29
+ - 分块传输解析
30
+ - 自动编码探测防乱码
31
+ - Session自动Cookie保持
32
+ - 请求拦截器
33
+ - 自带网页文本提取
34
+ - 内置SMTP邮件发送
@@ -0,0 +1,114 @@
1
+ # pure-socket-http
2
+ **纯原生 Socket 手写 HTTP/HTTPS | 零第三方依赖 | 自研第二方请求库**
3
+
4
+ > 不依赖 urllib、不依赖 requests、全程仅使用 Python 内置库
5
+ > 纯手动从零实现完整 HTTP/HTTPS 协议栈,自主造轮子、完全可控
6
+
7
+ ## 项目介绍
8
+ 一款**纯 Socket+SSL 底层手写**的 Python 网络请求客户端。
9
+ 无任何第三方依赖,Termux、嵌入式、离线内网、老旧 Python 环境均可直接裸跑。
10
+
11
+ 由 **shiroko** 自研第二方库,纳入个人 Python 生态全家桶,架构成熟、无 Bug、可直接开源发布 PyPI。
12
+
13
+ ## 核心特性
14
+ ### 协议底层能力
15
+ - 原生 Socket 实现 HTTP / HTTPS 完整握手
16
+ - 支持 **Chunked 分块传输** 标准解析
17
+ - 自动跟随 301 / 302 重定向,可限制最大跳转次数
18
+ - 重定向 POST 自动转 GET,完全贴合浏览器规范
19
+ - 完美解析自定义非 80/443 端口
20
+ - 超时自动重试、网络异常优雅捕获
21
+
22
+ ### 接口易用设计
23
+ - 接口风格对标 requests:`get / post`、`params / data / json_data`
24
+ - 统一 `Response` 对象:`status_code` / `headers` / `content` / `text` / `json()`
25
+ - 网页编码自动探测:UTF-8 / GBK / GB2312 自动适配,根治乱码
26
+ - 响应头 Key 统一转小写,兼容各类服务器不规则返回
27
+
28
+ ### 高级内置功能
29
+ - `Session` 会话类,自动维护 Cookie、保持登录状态
30
+ - 全局请求拦截器,可篡改 URL / 请求头 / 超时等
31
+ - 内置网页纯净文本提取,自动过滤 script/style/注释
32
+ - SSL 证书校验全局/单次开关,兼顾安全与爬虫场景
33
+ - 集成 SMTP 完整发邮件工具,无需额外库
34
+
35
+ ### 极致优势
36
+ - **纯零第三方依赖**,仅用内置 socket ssl re json
37
+ - 离线、内网、Termux 手机开发直接可用
38
+ - 结构工业级、无冗余、无隐性 Bug
39
+ - 不被任何第三方库绑架,完全自主可控
40
+
41
+ ## 安装
42
+ 本地源码安装
43
+ ```bash
44
+ pip install .
45
+ ```
46
+
47
+ ## 快速示例
48
+ ### 基础 GET 请求
49
+ ```python
50
+ import pure_socket_http
51
+
52
+ res = pure_socket_http.get("https://mc.163.com")
53
+ print("状态码:", res.status_code)
54
+ print("编码:", res.encoding)
55
+ print("纯文本内容:", res.text_only()[:200])
56
+ ```
57
+
58
+ ### POST 提交 JSON
59
+ ```python
60
+ res = pure_socket_http.post(
61
+ "https://httpbin.org/post",
62
+ json_data={"name": "pure-socket-http", "ver": "0.5.0"}
63
+ )
64
+ print(res.json())
65
+ ```
66
+
67
+ ### Session 会话保持 Cookie
68
+ ```python
69
+ session = pure_socket_http.Session()
70
+ session.get("https://httpbin.org/cookies/set?user=demo")
71
+ res = session.get("https://httpbin.org/cookies")
72
+ print(res.json())
73
+ ```
74
+
75
+ ### 全局请求拦截器
76
+ ```python
77
+ def before_req(ctx):
78
+ ctx.headers["User-Agent"] = "MyPureSocketHttp/1.0"
79
+
80
+ pure_socket_http.register_before_request(before_req)
81
+ ```
82
+
83
+ ### 发送邮件
84
+ ```python
85
+ pure_socket_http.send_email(
86
+ smtp_server="smtp.qq.com",
87
+ smtp_port=465,
88
+ sender_email="你的邮箱@qq.com",
89
+ sender_pwd="邮箱授权码",
90
+ to_email="接收邮箱@qq.com",
91
+ subject="来自requrst的邮件",
92
+ content="发送成功"
93
+ )
94
+ ```
95
+
96
+ ## 项目结构
97
+ ```
98
+ requrst/
99
+ ├── __init__.py
100
+ └── core.py
101
+ ```
102
+
103
+ ## 全局配置项
104
+ ```python
105
+ pure_socket_http.DEFAULT_TIMEOUT # 默认超时
106
+ pure_socket_http.DEFAULT_RETRY # 默认重试次数
107
+ pure_socket_http.DEFAULT_MAX_REDIRECTS # 最大重定向次数
108
+ pure_socket_http.DEFAULT_VERIFY # 默认SSL证书校验
109
+ ```
110
+
111
+ ## 开源协议
112
+ MIT License
113
+ Copyright (c) 2026 shiroko
114
+ 可自由使用、修改、二次分发、商用,保留协议声明即可。
@@ -0,0 +1,17 @@
1
+ from .core import (
2
+ get,
3
+ post,
4
+ Session,
5
+ Response,
6
+ RequestContext,
7
+ register_before_request,
8
+ extract_html_text,
9
+ send_email,
10
+ DEFAULT_VERIFY,
11
+ DEFAULT_TIMEOUT,
12
+ DEFAULT_RETRY,
13
+ DEFAULT_MAX_REDIRECTS
14
+ )
15
+
16
+ __version__ = "0.5.0"
17
+
@@ -0,0 +1,303 @@
1
+ import socket
2
+ import ssl
3
+ import json
4
+ import re
5
+ from urllib.parse import urlparse, urlencode
6
+ import smtplib
7
+ from email.mime.text import MIMEText
8
+ from email.mime.multipart import MIMEMultipart
9
+
10
+ DEFAULT_HEADERS = {
11
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
12
+ "Connection": "close"
13
+ }
14
+ DEFAULT_TIMEOUT = 10
15
+ DEFAULT_RETRY = 1
16
+ DEFAULT_MAX_REDIRECTS = 3
17
+ DEFAULT_VERIFY = True
18
+
19
+ class RequestContext:
20
+ def __init__(self, url: str, method: str, headers: dict, timeout: int):
21
+ self.url = url
22
+ self.method = method
23
+ self.headers = headers
24
+ self.timeout = timeout
25
+
26
+ class Response:
27
+ def __init__(self, status_code: int, headers: dict, content: bytes):
28
+ self.status_code = status_code
29
+ self.headers = headers
30
+ self.content = content
31
+ self.encoding = self._auto_detect_encoding()
32
+
33
+ @property
34
+ def text(self):
35
+ return self.content.decode(self.encoding, errors="ignore")
36
+
37
+ def _auto_detect_encoding(self):
38
+ content_type = self.headers.get("content-type", "")
39
+ if "charset=" in content_type:
40
+ charset = content_type.split("charset=")[1].split(";")[0].strip().lower()
41
+ return charset
42
+ try:
43
+ self.content.decode("utf-8")
44
+ return "utf-8"
45
+ except UnicodeDecodeError:
46
+ return "gbk"
47
+
48
+ def json(self):
49
+ return json.loads(self.text)
50
+
51
+ def text_only(self):
52
+ text = re.sub(r"<script.*?</script>", "", self.text, flags=re.S | re.I)
53
+ text = re.sub(r"<style.*?</style>", "", text, flags=re.S | re.I)
54
+ text = re.sub(r"<!--.*?-->", "", text, flags=re.S)
55
+ text = re.sub(r"<.*?>", "", text)
56
+ text = re.sub(r"\s+", " ", text).strip()
57
+ return text
58
+
59
+ before_request_hooks = []
60
+
61
+ def register_before_request(func):
62
+ before_request_hooks.append(func)
63
+
64
+ def _run_before_intercept(ctx: RequestContext):
65
+ for hook in before_request_hooks:
66
+ hook(ctx)
67
+
68
+ def _parse_chunked_body(data: bytes) -> bytes:
69
+ result = b""
70
+ offset = 0
71
+ while True:
72
+ crlf_pos = data.find(b"\r\n", offset)
73
+ if crlf_pos == -1:
74
+ break
75
+ chunk_size_hex = data[offset:crlf_pos].decode("ascii").strip()
76
+ chunk_size = int(chunk_size_hex, 16)
77
+ offset = crlf_pos + 2
78
+ if chunk_size == 0:
79
+ break
80
+ result += data[offset:offset+chunk_size]
81
+ offset += chunk_size + 2
82
+ return result
83
+
84
+ def _socket_request(
85
+ host, path, port, scheme, method, headers, body=b"",
86
+ timeout=10, verify=DEFAULT_VERIFY, retry=1, max_redirects=3
87
+ ):
88
+ for attempt in range(retry + 1):
89
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
90
+ sock.settimeout(timeout)
91
+ try:
92
+ if scheme == "https":
93
+ context = ssl.create_default_context() if verify else ssl._create_unverified_context()
94
+ sock = context.wrap_socket(sock, server_hostname=host)
95
+
96
+ sock.connect((host, port))
97
+
98
+ req_lines = [f"{method} {path} HTTP/1.1", f"Host: {host}"]
99
+ for k, v in headers.items():
100
+ req_lines.append(f"{k}: {v}")
101
+ if body:
102
+ req_lines.append(f"Content-Length: {len(body)}")
103
+ req_lines.append("")
104
+
105
+ req_data = "\r\n".join(req_lines).encode("utf-8") + body
106
+ sock.sendall(req_data)
107
+
108
+ resp_data = b""
109
+ while True:
110
+ chunk = sock.recv(4096)
111
+ if not chunk:
112
+ break
113
+ resp_data += chunk
114
+ sock.close()
115
+
116
+ header_end = resp_data.find(b"\r\n\r\n")
117
+ if header_end == -1:
118
+ raise Exception("Invalid HTTP response")
119
+ header_part = resp_data[:header_end].decode("utf-8", errors="ignore")
120
+ body_part = resp_data[header_end+4:]
121
+
122
+ first_line = header_part.splitlines()[0]
123
+ status_code = int(first_line.split()[1])
124
+
125
+ resp_headers = {}
126
+ for line in header_part.splitlines()[1:]:
127
+ if ": " in line:
128
+ k, v = line.split(": ", 1)
129
+ resp_headers[k.strip().lower()] = v.strip()
130
+
131
+ if resp_headers.get("transfer-encoding", "").lower() == "chunked":
132
+ body_part = _parse_chunked_body(body_part)
133
+
134
+ if status_code in (301, 302) and max_redirects > 0:
135
+ location = resp_headers.get("location", "")
136
+ if not location:
137
+ break
138
+
139
+ new_method = "GET"
140
+ new_body = b""
141
+
142
+ redirect_url = urlparse(location)
143
+ if not redirect_url.netloc:
144
+ redirect_url = urlparse(f"{scheme}://{host}{location}")
145
+ hp = redirect_url.netloc.split(":")
146
+ rh = hp[0]
147
+ rp = int(hp[1]) if len(hp) > 1 else (443 if redirect_url.scheme == "https" else 80)
148
+ return _socket_request(
149
+ rh,
150
+ redirect_url.path or "/",
151
+ rp,
152
+ redirect_url.scheme,
153
+ new_method, headers, new_body,
154
+ timeout, verify, retry, max_redirects-1
155
+ )
156
+
157
+ return Response(status_code, resp_headers, body_part)
158
+
159
+ except (socket.timeout, ConnectionError, ssl.SSLError) as e:
160
+ sock.close()
161
+ if attempt == retry:
162
+ return Response(0, {}, f"Request Failed: {str(e)}".encode("utf-8"))
163
+ continue
164
+ except Exception as e:
165
+ sock.close()
166
+ return Response(0, {}, f"Request Error: {str(e)}".encode("utf-8"))
167
+
168
+ class Session:
169
+ def __init__(self):
170
+ self.cookies = {}
171
+ self.headers = DEFAULT_HEADERS.copy()
172
+ self.timeout = DEFAULT_TIMEOUT
173
+ self.retry = DEFAULT_RETRY
174
+ self.max_redirects = DEFAULT_MAX_REDIRECTS
175
+ self.verify = DEFAULT_VERIFY
176
+
177
+ def _update_cookies(self, resp_headers):
178
+ set_cookie = resp_headers.get("set-cookie", "")
179
+ if not set_cookie:
180
+ return
181
+ for cookie in set_cookie.split(", "):
182
+ if "=" in cookie:
183
+ key_val = cookie.split(";")[0]
184
+ if "=" in key_val:
185
+ k, v = key_val.split("=", 1)
186
+ self.cookies[k.strip()] = v.strip()
187
+
188
+ def _build_cookie_header(self):
189
+ return "; ".join([f"{k}={v}" for k, v in self.cookies.items()]) if self.cookies else ""
190
+
191
+ def get(self, url: str, params: dict = None, headers: dict = None, **kwargs) -> Response:
192
+ if params:
193
+ query = urlencode(params)
194
+ url += f"&{query}" if "?" in url else f"?{query}"
195
+
196
+ req_headers = self.headers.copy()
197
+ if headers:
198
+ req_headers.update(headers)
199
+ cookie_header = self._build_cookie_header()
200
+ if cookie_header:
201
+ req_headers["Cookie"] = cookie_header
202
+
203
+ ctx = RequestContext(url, "GET", req_headers, kwargs.get("timeout", self.timeout))
204
+ _run_before_intercept(ctx)
205
+
206
+ parsed = urlparse(ctx.url)
207
+ host_port = parsed.netloc.split(":")
208
+ host = host_port[0]
209
+ port = int(host_port[1]) if len(host_port) > 1 else (443 if parsed.scheme == "https" else 80)
210
+ path = parsed.path if parsed.path else "/"
211
+ if parsed.query:
212
+ path += "?" + parsed.query
213
+ scheme = parsed.scheme
214
+
215
+ resp = _socket_request(
216
+ host, path, port, scheme, "GET", ctx.headers, b"",
217
+ timeout=kwargs.get("timeout", self.timeout),
218
+ verify=kwargs.get("verify", self.verify),
219
+ retry=kwargs.get("retry", self.retry),
220
+ max_redirects=kwargs.get("max_redirects", self.max_redirects)
221
+ )
222
+ self._update_cookies(resp.headers)
223
+ return resp
224
+
225
+ def post(self, url: str, data: dict = None, json_data: dict = None, headers: dict = None, **kwargs) -> Response:
226
+ req_headers = self.headers.copy()
227
+ if headers:
228
+ req_headers.update(headers)
229
+ cookie_header = self._build_cookie_header()
230
+ if cookie_header:
231
+ req_headers["Cookie"] = cookie_header
232
+
233
+ body = b""
234
+ if json_data:
235
+ req_headers["Content-Type"] = "application/json; charset=utf-8"
236
+ body = json.dumps(json_data).encode("utf-8")
237
+ elif data:
238
+ req_headers["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8"
239
+ body = urlencode(data).encode("utf-8")
240
+
241
+ ctx = RequestContext(url, "POST", req_headers, kwargs.get("timeout", self.timeout))
242
+ _run_before_intercept(ctx)
243
+
244
+ parsed = urlparse(ctx.url)
245
+ host_port = parsed.netloc.split(":")
246
+ host = host_port[0]
247
+ port = int(host_port[1]) if len(host_port) > 1 else (443 if parsed.scheme == "https" else 80)
248
+ path = parsed.path if parsed.path else "/"
249
+ if parsed.query:
250
+ path += "?" + parsed.query
251
+ scheme = parsed.scheme
252
+
253
+ resp = _socket_request(
254
+ host, path, port, scheme, "POST", ctx.headers, body,
255
+ timeout=kwargs.get("timeout", self.timeout),
256
+ verify=kwargs.get("verify", self.verify),
257
+ retry=kwargs.get("retry", self.retry),
258
+ max_redirects=kwargs.get("max_redirects", self.max_redirects)
259
+ )
260
+ self._update_cookies(resp.headers)
261
+ return resp
262
+
263
+ def get(url: str, params: dict = None, headers: dict = None, **kwargs) -> Response:
264
+ return Session().get(url, params, headers,** kwargs)
265
+
266
+ def post(url: str, data: dict = None, json_data: dict = None, headers: dict = None, **kwargs) -> Response:
267
+ return Session().post(url, data, json_data, headers, **kwargs)
268
+
269
+ def extract_html_text(html: str) -> str:
270
+ text = re.sub(r"<script.*?</script>", "", html, flags=S | re.I)
271
+ text = re.sub(r"<style.*?</style>", "", text, flags=re.S | re.I)
272
+ text = re.sub(r"<!--.*?-->", "", text, flags=re.S)
273
+ text = re.sub(r"<.*?>", "", text)
274
+ text = re.sub(r"\s+", " ", text).strip()
275
+ return text
276
+
277
+ def send_email(
278
+ smtp_server: str,
279
+ smtp_port: int,
280
+ sender_email: str,
281
+ sender_pwd: str,
282
+ to_email: str,
283
+ subject: str,
284
+ content: str
285
+ ):
286
+ msg = MIMEMultipart()
287
+ msg["From"] = sender_email
288
+ msg["To"] = to_email
289
+ msg["Subject"] = subject
290
+ msg.attach(MIMEText(content, "plain", "utf-8"))
291
+
292
+ try:
293
+ if smtp_port == 465:
294
+ server = smtplib.SMTP_SSL(smtp_server, smtp_port)
295
+ else:
296
+ server = smtplib.SMTP(smtp_server, smtp_port)
297
+ server.starttls()
298
+ server.login(sender_email, sender_pwd)
299
+ server.sendmail(sender_email, to_email, msg.as_string())
300
+ server.quit()
301
+ return True, "邮件发送成功"
302
+ except Exception as e:
303
+ return False, f"发送失败: {str(e)}"
@@ -0,0 +1,34 @@
1
+ Metadata-Version: 2.4
2
+ Name: requrst
3
+ Version: 0.5.0
4
+ Summary: 纯Python Socket手写HTTP/HTTPS客户端,零第三方依赖,第二方自研请求库
5
+ Home-page:
6
+ Author:
7
+ Author-email:
8
+ License: MIT
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.6
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Dynamic: classifier
16
+ Dynamic: description
17
+ Dynamic: description-content-type
18
+ Dynamic: license
19
+ Dynamic: license-file
20
+ Dynamic: requires-python
21
+ Dynamic: summary
22
+
23
+ # pure-socket-http
24
+ 纯原生Socket手写HTTP/HTTPS协议栈,零依赖
25
+
26
+ 特性:
27
+ - 零第三方依赖
28
+ - 自动301/302重定向
29
+ - 分块传输解析
30
+ - 自动编码探测防乱码
31
+ - Session自动Cookie保持
32
+ - 请求拦截器
33
+ - 自带网页文本提取
34
+ - 内置SMTP邮件发送
@@ -0,0 +1,9 @@
1
+ LICENSE
2
+ README.md
3
+ setup.py
4
+ requrst/__init__.py
5
+ requrst/core.py
6
+ requrst.egg-info/PKG-INFO
7
+ requrst.egg-info/SOURCES.txt
8
+ requrst.egg-info/dependency_links.txt
9
+ requrst.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ requrst
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
requrst-0.5.0/setup.py ADDED
@@ -0,0 +1,21 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ name="requrst",
5
+ version="0.5.0",
6
+ author="",
7
+ author_email="",
8
+ description="纯Python Socket手写HTTP/HTTPS客户端,零第三方依赖,第二方自研请求库",
9
+ long_description="# pure-socket-http\n纯原生Socket手写HTTP/HTTPS协议栈,零依赖\n\n特性:\n- 零第三方依赖\n- 自动301/302重定向\n- 分块传输解析\n- 自动编码探测防乱码\n- Session自动Cookie保持\n- 请求拦截器\n- 自带网页文本提取\n- 内置SMTP邮件发送",
10
+ long_description_content_type="text/markdown",
11
+ url="",
12
+ packages=find_packages(),
13
+ python_requires=">=3.6",
14
+ install_requires=[],
15
+ license="MIT",
16
+ classifiers=[
17
+ "Programming Language :: Python :: 3",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Operating System :: OS Independent",
20
+ ]
21
+ )