requrst 0.5.0__py3-none-any.whl

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/__init__.py ADDED
@@ -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
+
requrst/core.py ADDED
@@ -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,7 @@
1
+ requrst/__init__.py,sha256=pjIor-6IdFPQ8d9Tbe1VOx2X_n1adSaNbBTG5cU_RE8,266
2
+ requrst/core.py,sha256=pqcoi_IBr3yVoDx6t7G48PTkAKOedh68qG3Zcbi52jY,11135
3
+ requrst-0.5.0.dist-info/licenses/LICENSE,sha256=tQ-0w6byZoWSN8dbgiUAlwlXAacv5McP5Q16RR8cB4w,1064
4
+ requrst-0.5.0.dist-info/METADATA,sha256=LzC_g9gAtgCRVt6RY5cOcujfQsVEQ2WQglrbedyrTrA,865
5
+ requrst-0.5.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
6
+ requrst-0.5.0.dist-info/top_level.txt,sha256=X010-22ipGcj_Z2XyZEQFs-zXbb-neqx23Pg4BjWHZc,8
7
+ requrst-0.5.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -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.
@@ -0,0 +1 @@
1
+ requrst