tls-client-python 1.15.0.4__tar.gz → 1.15.1__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.
Files changed (24) hide show
  1. {tls_client_python-1.15.0.4/tls_client_python.egg-info → tls_client_python-1.15.1}/PKG-INFO +1 -1
  2. {tls_client_python-1.15.0.4 → tls_client_python-1.15.1}/tls_client/__init__.py +1 -1
  3. {tls_client_python-1.15.0.4 → tls_client_python-1.15.1}/tls_client/_core.py +381 -160
  4. {tls_client_python-1.15.0.4 → tls_client_python-1.15.1}/tls_client/bin/tls-client-darwin-amd64.dylib +0 -0
  5. {tls_client_python-1.15.0.4 → tls_client_python-1.15.1}/tls_client/bin/tls-client-darwin-arm64.dylib +0 -0
  6. {tls_client_python-1.15.0.4 → tls_client_python-1.15.1}/tls_client/bin/tls-client-linux-amd64-musl.so +0 -0
  7. {tls_client_python-1.15.0.4 → tls_client_python-1.15.1}/tls_client/bin/tls-client-linux-amd64.so +0 -0
  8. tls_client_python-1.15.1/tls_client/bin/tls-client-windows-386.dll +0 -0
  9. tls_client_python-1.15.1/tls_client/bin/tls-client-windows-amd64.dll +0 -0
  10. {tls_client_python-1.15.0.4 → tls_client_python-1.15.1/tls_client_python.egg-info}/PKG-INFO +1 -1
  11. tls_client_python-1.15.0.4/tls_client/bin/tls-client-windows-386.dll +0 -0
  12. tls_client_python-1.15.0.4/tls_client/bin/tls-client-windows-amd64.dll +0 -0
  13. {tls_client_python-1.15.0.4 → tls_client_python-1.15.1}/LICENSE +0 -0
  14. {tls_client_python-1.15.0.4 → tls_client_python-1.15.1}/MANIFEST.in +0 -0
  15. {tls_client_python-1.15.0.4 → tls_client_python-1.15.1}/Readme.md +0 -0
  16. {tls_client_python-1.15.0.4 → tls_client_python-1.15.1}/pyproject.toml +0 -0
  17. {tls_client_python-1.15.0.4 → tls_client_python-1.15.1}/setup.cfg +0 -0
  18. {tls_client_python-1.15.0.4 → tls_client_python-1.15.1}/setup.py +0 -0
  19. {tls_client_python-1.15.0.4 → tls_client_python-1.15.1}/tls_client/_default_headers.py +0 -0
  20. {tls_client_python-1.15.0.4 → tls_client_python-1.15.1}/tls_client_python.egg-info/SOURCES.txt +0 -0
  21. {tls_client_python-1.15.0.4 → tls_client_python-1.15.1}/tls_client_python.egg-info/dependency_links.txt +0 -0
  22. {tls_client_python-1.15.0.4 → tls_client_python-1.15.1}/tls_client_python.egg-info/not-zip-safe +0 -0
  23. {tls_client_python-1.15.0.4 → tls_client_python-1.15.1}/tls_client_python.egg-info/requires.txt +0 -0
  24. {tls_client_python-1.15.0.4 → tls_client_python-1.15.1}/tls_client_python.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tls-client-python
3
- Version: 1.15.0.4
3
+ Version: 1.15.1
4
4
  Summary: High-performance Python binding for bogdanfinn/tls-client via CFFI – zero-copy, panic-proof, full TLS fingerprint control
5
5
  Author: komAAmok
6
6
  License-Expression: MIT
@@ -25,4 +25,4 @@ __all__ = [
25
25
  "ClientIdentifiers",
26
26
  "clear_client_pool",
27
27
  ]
28
- __version__ = "1.15.0.4"
28
+ __version__ = "1.15.1"
@@ -34,7 +34,7 @@ import platform
34
34
  import sys
35
35
  import threading
36
36
  from pathlib import Path
37
- from typing import Any, Dict, List, Literal, Optional
37
+ from typing import Any, Dict, List, Optional, Tuple, Union
38
38
  import hashlib
39
39
 
40
40
  from tls_client._default_headers import DEFAULT_HEADERS
@@ -1232,115 +1232,6 @@ def _compute_cache_key_hash(r: dict) -> str:
1232
1232
  return h.hexdigest()
1233
1233
 
1234
1234
 
1235
- # ---------------------------------------------------------------------------
1236
- # Shared RequestOptions builder — eliminates ~80 lines of duplicated
1237
- # C‑struct logic between Session.execute_request and AsyncSession._execute_async
1238
- # ---------------------------------------------------------------------------
1239
-
1240
- def _populate_request_options(
1241
- ffi: Any,
1242
- opts: Any,
1243
- keep_alive: list,
1244
- defaults: Dict[str, Any],
1245
- overrides: Dict[str, Any],
1246
- ) -> None:
1247
- """Set every field on *opts* by looking up ``overrides[name]`` first,
1248
- then falling back to ``defaults[name]``. Bool fields are auto‑converted
1249
- to C ``int`` (0/1). String / array / dict fields call the appropriate
1250
- ``_build_*`` helper and extend *keep_alive*."""
1251
-
1252
- def _val(name: str, as_bool: bool = False) -> Any:
1253
- v = overrides.get(name)
1254
- if v is None:
1255
- v = defaults.get(name) # defensive: missing key → None instead of KeyError
1256
- if as_bool:
1257
- return 1 if v else 0
1258
- return v
1259
-
1260
- # ---- String fields (nullable C strings) -------------------------------
1261
- for field in (
1262
- "proxy",
1263
- "client_identifier",
1264
- "server_name_overwrite",
1265
- "request_host_override",
1266
- "local_address",
1267
- ):
1268
- c_val = _c_string(ffi, _val(field))
1269
- setattr(opts, field, c_val)
1270
- if c_val != ffi.NULL:
1271
- keep_alive.append(c_val)
1272
-
1273
- # ---- Array / dict fields (C arrays of structs) ------------------------
1274
- (
1275
- opts.pseudo_header_order,
1276
- opts.pseudo_header_order_len,
1277
- ) = _build_string_array(ffi, _val("pseudo_header_order"), keep_alive)
1278
-
1279
- (
1280
- opts.h3_pseudo_header_order,
1281
- opts.h3_pseudo_header_order_len,
1282
- ) = _build_string_array(ffi, _val("h3_pseudo_header_order"), keep_alive)
1283
-
1284
- opts.default_headers, opts.default_headers_len = _build_headers(
1285
- ffi, _val("default_headers"), keep_alive
1286
- )
1287
- opts.connect_headers, opts.connect_headers_len = _build_headers(
1288
- ffi, _val("connect_headers"), keep_alive
1289
- )
1290
- (
1291
- opts.certificate_pinning_hosts,
1292
- opts.certificate_pinning_hosts_len,
1293
- ) = _build_pin_entries(
1294
- ffi, _val("certificate_pinning_hosts"), keep_alive
1295
- )
1296
- opts.request_cookies, opts.request_cookies_len = _build_headers(
1297
- ffi, _val("request_cookies"), keep_alive
1298
- )
1299
- (
1300
- opts.client_certificates,
1301
- opts.client_certificates_len,
1302
- ) = _build_client_certificates(
1303
- ffi, _val("client_certificates"), keep_alive
1304
- )
1305
- opts.custom_tls_client = _build_custom_tls_client(
1306
- ffi, _val("custom_tls_client"), keep_alive
1307
- )
1308
-
1309
- # ---- Scalar fields (int / bool→int) -----------------------------------
1310
- opts.timeout_seconds = _val("timeout_seconds")
1311
- opts.timeout_milliseconds = _val("timeout_milliseconds")
1312
- opts.follow_redirects = _val("follow_redirects", True)
1313
- opts.insecure_skip_verify = _val("insecure_skip_verify", True)
1314
- opts.force_http1 = _val("force_http1", True)
1315
- opts.with_random_tls_extension_order = _val(
1316
- "with_random_tls_extension_order", True
1317
- )
1318
- opts.with_protocol_racing = _val("with_protocol_racing", True)
1319
- opts.with_default_bad_pin_handler = _val(
1320
- "with_default_bad_pin_handler", True
1321
- )
1322
- opts.max_idle_connections = _val("max_idle_connections")
1323
- opts.max_idle_connections_per_host = _val("max_idle_connections_per_host")
1324
- opts.max_connections_per_host = _val("max_connections_per_host")
1325
- opts.disable_keep_alives = _val("disable_keep_alives", True)
1326
- opts.disable_compression = _val("disable_compression", True)
1327
- opts.idle_conn_timeout_seconds = _val("idle_conn_timeout_seconds")
1328
- opts.max_response_header_bytes = _val("max_response_header_bytes")
1329
- opts.write_buffer_size = _val("write_buffer_size")
1330
- opts.read_buffer_size = _val("read_buffer_size")
1331
- opts.allow_empty_cookies = _val("allow_empty_cookies", True)
1332
- opts.without_cookie_jar = _val("without_cookie_jar", True)
1333
- opts.disable_http3 = _val("disable_http3", True)
1334
- opts.disable_ipv4 = _val("disable_ipv4", True)
1335
- opts.disable_ipv6 = _val("disable_ipv6", True)
1336
- opts.tcp_ttl = _val("tcp_ttl")
1337
- opts.tcp_window_size = _val("tcp_window_size")
1338
- opts.tcp_window_scale = _val("tcp_window_scale")
1339
- opts.tcp_mss = _val("tcp_mss")
1340
- opts.catch_panics = _val("catch_panics", True)
1341
- opts.with_debug = _val("with_debug", True)
1342
-
1343
-
1344
1235
  # ---------------------------------------------------------------------------
1345
1236
  # Response unpacking — shared between sync ExecuteRequest and async callback
1346
1237
  # ---------------------------------------------------------------------------
@@ -1843,6 +1734,53 @@ class Session:
1843
1734
  def with_debug(self, value: bool) -> None:
1844
1735
  self.defaults["with_debug"] = 1 if value else 0
1845
1736
 
1737
+ # -- auth ----------------------------------------------------------------
1738
+
1739
+ @property
1740
+ def auth(self) -> Optional[Tuple[str, str]]:
1741
+ """HTTP 认证元组 ``(username, password)`` / HTTP auth tuple ``(username, password)``."""
1742
+ return self.defaults.get("auth")
1743
+
1744
+ @auth.setter
1745
+ def auth(self, value: Optional[Tuple[str, str]]) -> None:
1746
+ self.defaults["auth"] = value
1747
+
1748
+ # -- params (query string) ----------------------------------------------
1749
+
1750
+ @property
1751
+ def params(self) -> Optional[Dict[str, str]]:
1752
+ """查询字符串参数字典 / Query-string parameter dict."""
1753
+ return self.defaults.get("params")
1754
+
1755
+ @params.setter
1756
+ def params(self, value: Optional[Dict[str, str]]) -> None:
1757
+ self.defaults["params"] = value
1758
+
1759
+ # -- cert (client SSL certificate) --------------------------------------
1760
+
1761
+ @property
1762
+ def cert(self) -> Optional[Union[str, Tuple[str, str]]]:
1763
+ """客户端 SSL 证书路径 / Client SSL cert path.
1764
+
1765
+ ``str``: 单独 cert 文件 ; ``(cert_path, key_path)``: cert + key 文件。
1766
+ """
1767
+ return self.defaults.get("cert")
1768
+
1769
+ @cert.setter
1770
+ def cert(self, value: Optional[Union[str, Tuple[str, str]]]) -> None:
1771
+ self.defaults["cert"] = value
1772
+
1773
+ # -- stream (response streaming mode) -----------------------------------
1774
+
1775
+ @property
1776
+ def stream(self) -> bool:
1777
+ """是否流式读取响应体 / Whether to stream the response body."""
1778
+ return bool(self.defaults.get("stream", False))
1779
+
1780
+ @stream.setter
1781
+ def stream(self, value: bool) -> None:
1782
+ self.defaults["stream"] = 1 if value else 0
1783
+
1846
1784
  def __init__(
1847
1785
  self,
1848
1786
  *,
@@ -1936,6 +1874,15 @@ class Session:
1936
1874
  allow_empty_cookies: bool = False,
1937
1875
  # 完全禁用 Cookie Jar / Completely disable Cookie Jar
1938
1876
  without_cookie_jar: bool = False,
1877
+ # ── requests 兼容属性 ── / requests-compatible properties ──
1878
+ # HTTP 认证元组 (username, password) / HTTP auth tuple
1879
+ auth: Optional[Tuple[str, str]] = None,
1880
+ # 查询字符串参数字典 / Query-string parameter dict
1881
+ params: Optional[Dict[str, str]] = None,
1882
+ # 客户端 SSL 证书路径 / Client SSL cert path
1883
+ cert: Optional[Union[str, Tuple[str, str]]] = None,
1884
+ # 是否流式读取响应体 / Whether to stream the response body
1885
+ stream: bool = False,
1939
1886
  # ── 调试 / 安全 ── / Debug / Safety ──
1940
1887
  # 是否在 Go 侧捕获 panic / Whether to catch Go panics
1941
1888
  catch_panics: bool = True,
@@ -1959,6 +1906,10 @@ class Session:
1959
1906
  "proxy": proxy,
1960
1907
  "pseudo_header_order": pseudo_header_order,
1961
1908
  "h3_pseudo_header_order": h3_pseudo_header_order,
1909
+ "auth": auth,
1910
+ "params": params,
1911
+ "cert": cert,
1912
+ "stream": 1 if stream else 0,
1962
1913
  "default_headers": (
1963
1914
  default_headers
1964
1915
  if default_headers is not None
@@ -2415,6 +2366,139 @@ class Session:
2415
2366
  def patch(self, url: str, *, headers: Optional[Dict[str, str]] = None, body: Optional[bytes] = None, **kwargs: Any) -> Response:
2416
2367
  return self.execute_request("PATCH", url, headers=headers, body=body, **kwargs)
2417
2368
 
2369
+ def request(
2370
+ self,
2371
+ method: str,
2372
+ url: str,
2373
+ *,
2374
+ params: Optional[Dict[str, str]] = None,
2375
+ data: Union[bytes, str, Dict[str, str], None] = None,
2376
+ json: Any = None,
2377
+ headers: Optional[Dict[str, str]] = None,
2378
+ auth: Optional[Tuple[str, str]] = None,
2379
+ cookies: Optional[Dict[str, str]] = None,
2380
+ stream: Optional[bool] = None,
2381
+ cert: Optional[Union[str, Tuple[str, str]]] = None,
2382
+ timeout: Optional[int] = None,
2383
+ allow_redirects: Optional[bool] = None,
2384
+ proxies: Optional[Dict[str, str]] = None,
2385
+ verify: Optional[bool] = None,
2386
+ **kwargs: Any,
2387
+ ) -> Response:
2388
+ """``requests`` 兼容的通用 HTTP 请求方法。
2389
+
2390
+ ``requests``-compatible universal HTTP request method.
2391
+
2392
+ 支持 ``params``、``data``、``json``、``auth``、``cookies``、``cert``、
2393
+ ``proxies``、``allow_redirects``、``timeout``、``verify`` 等标准参数。
2394
+ 每个参数都会映射到 ``execute_request`` 的内部参数名。
2395
+ """
2396
+ # ── params: append to URL query string ────────────────────────────
2397
+ if params:
2398
+ from urllib.parse import urlencode, urlparse, urlunparse
2399
+ parsed = urlparse(url)
2400
+ merged = dict(
2401
+ (k, v) for k, v in (p.split("=", 1) for p in parsed.query.split("&") if p)
2402
+ )
2403
+ merged.update(params)
2404
+ url = urlunparse(parsed._replace(
2405
+ query=urlencode([(k, v) for k, v in merged.items()])
2406
+ ))
2407
+
2408
+ # ── body: data / json ─────────────────────────────────────────────
2409
+ body = kwargs.pop("body", None)
2410
+ if body is None and data is not None:
2411
+ if isinstance(data, dict):
2412
+ from urllib.parse import urlencode
2413
+ body = urlencode(data).encode("utf-8")
2414
+ if headers is None:
2415
+ headers = {}
2416
+ if "Content-Type" not in {k.lower(): v for k, v in (headers or {}).items()}:
2417
+ headers = dict(headers or {})
2418
+ headers["Content-Type"] = "application/x-www-form-urlencoded"
2419
+ elif isinstance(data, str):
2420
+ body = data.encode("utf-8")
2421
+ else:
2422
+ body = data
2423
+ if json is not None:
2424
+ import json as _json
2425
+ body = _json.dumps(json, ensure_ascii=False).encode("utf-8")
2426
+ if headers is None:
2427
+ headers = {}
2428
+ if "Content-Type" not in {k.lower(): v for k, v in (headers or {}).items()}:
2429
+ headers = dict(headers or {})
2430
+ headers["Content-Type"] = "application/json"
2431
+
2432
+ # ── auth: Basic Auth header ───────────────────────────────────────
2433
+ _auth = auth if auth is not None else self.defaults.get("auth")
2434
+ if _auth is not None:
2435
+ import base64
2436
+ user, pwd = _auth
2437
+ encoded = base64.b64encode(f"{user}:{pwd}".encode("utf-8")).decode("ascii")
2438
+ if headers is None:
2439
+ headers = {}
2440
+ headers = dict(headers or {})
2441
+ headers.setdefault("Authorization", f"Basic {encoded}")
2442
+
2443
+ # ── cert: file path → client_certificates ────────────────────────
2444
+ _cert = cert if cert is not None else self.defaults.get("cert")
2445
+ client_certificates = kwargs.pop("client_certificates", None)
2446
+ if client_certificates is None and _cert is not None:
2447
+ if isinstance(_cert, str):
2448
+ with open(_cert, "rb") as f:
2449
+ cert_bytes = f.read()
2450
+ client_certificates = [{"cert_pem": cert_bytes, "key_pem": cert_bytes}]
2451
+ elif isinstance(_cert, tuple) and len(_cert) == 2:
2452
+ with open(_cert[0], "rb") as f:
2453
+ cert_bytes = f.read()
2454
+ with open(_cert[1], "rb") as f:
2455
+ key_bytes = f.read()
2456
+ client_certificates = [{"cert_pem": cert_bytes, "key_pem": key_bytes}]
2457
+
2458
+ # ── cookies ──────────────────────────────────────────────────────
2459
+ _cookies = cookies if cookies is not None else kwargs.pop("request_cookies", None)
2460
+ kwargs.pop("request_cookies", None) # guard against duplicate kwarg in **kwargs
2461
+
2462
+ # ── proxies (dict → single proxy string) ─────────────────────────
2463
+ _proxies = proxies
2464
+ if _proxies is not None:
2465
+ scheme = url.split(":", 1)[0].lower()
2466
+ proxy_url = _proxies.get(scheme) or _proxies.get("all") or next(
2467
+ iter(_proxies.values()), None
2468
+ )
2469
+ kwargs.setdefault("proxy", proxy_url)
2470
+
2471
+ # ── name mapping: requests → execute_request ─────────────────────
2472
+ if allow_redirects is not None:
2473
+ kwargs.setdefault("follow_redirects", allow_redirects)
2474
+ if timeout is not None:
2475
+ kwargs.setdefault("timeout", timeout)
2476
+ if verify is not None:
2477
+ kwargs.setdefault("verify", verify)
2478
+ if stream is not None:
2479
+ kwargs.setdefault("stream", stream)
2480
+
2481
+ return self.execute_request(
2482
+ method, url,
2483
+ headers=headers,
2484
+ body=body,
2485
+ request_cookies=_cookies,
2486
+ client_certificates=client_certificates,
2487
+ **kwargs,
2488
+ )
2489
+
2490
+ def options(self, url: str, **kwargs: Any) -> Response:
2491
+ """发送 HTTP OPTIONS 请求 / Send an HTTP OPTIONS request."""
2492
+ return self.request("OPTIONS", url, **kwargs)
2493
+
2494
+ def close(self) -> None:
2495
+ """关闭会话,释放 Go 客户端池中的空闲连接。
2496
+
2497
+ Close the session and release idle connections in the Go client pool.
2498
+ """
2499
+ _, lib = _get_ffi()
2500
+ lib.ClearClientPool()
2501
+
2418
2502
  @staticmethod
2419
2503
  def clear_client_pool() -> None:
2420
2504
  """Close all idle connections in the global Go client pool."""
@@ -2455,12 +2539,14 @@ class Session:
2455
2539
  _pending_requests: Dict[int, tuple] = {}
2456
2540
  _pending_lock = threading.Lock()
2457
2541
  _request_counter = 0
2542
+ _request_counter_lock = threading.Lock()
2458
2543
 
2459
2544
 
2460
2545
  def _next_request_id() -> int:
2461
2546
  global _request_counter
2462
- _request_counter += 1
2463
- return _request_counter
2547
+ with _request_counter_lock:
2548
+ _request_counter += 1
2549
+ return _request_counter
2464
2550
 
2465
2551
 
2466
2552
  def _resolve_async_response(ffi, future, raw_gc):
@@ -2699,6 +2785,15 @@ class AsyncSession:
2699
2785
  allow_empty_cookies: bool = False,
2700
2786
  # 完全禁用 Cookie Jar / Completely disable Cookie Jar
2701
2787
  without_cookie_jar: bool = False,
2788
+ # ── requests 兼容属性 ── / requests-compatible properties ──
2789
+ # HTTP 认证元组 (username, password) / HTTP auth tuple
2790
+ auth: Optional[Tuple[str, str]] = None,
2791
+ # 查询字符串参数字典 / Query-string parameter dict
2792
+ params: Optional[Dict[str, str]] = None,
2793
+ # 客户端 SSL 证书路径 / Client SSL cert path
2794
+ cert: Optional[Union[str, Tuple[str, str]]] = None,
2795
+ # 是否流式读取响应体 / Whether to stream the response body
2796
+ stream: bool = False,
2702
2797
  # ── 调试 / 安全 ── / Debug / Safety ──
2703
2798
  # 是否在 Go 侧捕获 panic / Whether to catch Go panics
2704
2799
  catch_panics: bool = True,
@@ -2745,6 +2840,10 @@ class AsyncSession:
2745
2840
  tcp_mss=tcp_mss,
2746
2841
  allow_empty_cookies=allow_empty_cookies,
2747
2842
  without_cookie_jar=without_cookie_jar,
2843
+ auth=auth,
2844
+ params=params,
2845
+ cert=cert,
2846
+ stream=stream,
2748
2847
  catch_panics=catch_panics,
2749
2848
  with_debug=with_debug,
2750
2849
  )
@@ -2818,6 +2917,57 @@ class AsyncSession:
2818
2917
  return 1 if v else 0
2819
2918
  return v
2820
2919
 
2920
+ # Pre-compute cache key BEFORE _val() consumes kwargs.
2921
+ # kwargs.get() is non-destructive so values remain for _val() below.
2922
+ def _ck(name):
2923
+ return kwargs.get(name, self._session.defaults.get(name))
2924
+ def _ckb(name):
2925
+ v = kwargs.get(name, self._session.defaults.get(name))
2926
+ return 1 if v else 0
2927
+ ck_hash = _compute_cache_key_hash({
2928
+ "client_identifier": _ck("client_identifier") or "",
2929
+ "proxy": _ck("proxy") or "",
2930
+ "server_name_overwrite": _ck("server_name_overwrite") or "",
2931
+ "local_address": _ck("local_address") or "",
2932
+ "insecure_skip_verify": _ckb("insecure_skip_verify"),
2933
+ "force_http1": _ckb("force_http1"),
2934
+ "with_random_tls_extension_order": _ckb("with_random_tls_extension_order"),
2935
+ "with_protocol_racing": _ckb("with_protocol_racing"),
2936
+ "max_idle_connections": _ck("max_idle_connections"),
2937
+ "max_idle_connections_per_host": _ck("max_idle_connections_per_host"),
2938
+ "max_connections_per_host": _ck("max_connections_per_host"),
2939
+ "max_response_header_bytes": _ck("max_response_header_bytes"),
2940
+ "write_buffer_size": _ck("write_buffer_size"),
2941
+ "read_buffer_size": _ck("read_buffer_size"),
2942
+ "idle_conn_timeout_seconds": _ck("idle_conn_timeout_seconds"),
2943
+ "disable_keep_alives": _ckb("disable_keep_alives"),
2944
+ "disable_compression": _ckb("disable_compression"),
2945
+ "disable_http3": _ckb("disable_http3"),
2946
+ "disable_ipv4": _ckb("disable_ipv4"),
2947
+ "disable_ipv6": _ckb("disable_ipv6"),
2948
+ "tcp_ttl": _ck("tcp_ttl"),
2949
+ "tcp_window_size": _ck("tcp_window_size"),
2950
+ "tcp_window_scale": _ck("tcp_window_scale"),
2951
+ "tcp_mss": _ck("tcp_mss"),
2952
+ "follow_redirects": _ckb("follow_redirects"),
2953
+ "without_cookie_jar": _ckb("without_cookie_jar"),
2954
+ "allow_empty_cookies": _ckb("allow_empty_cookies"),
2955
+ "with_default_bad_pin_handler": _ckb("with_default_bad_pin_handler"),
2956
+ "timeout_seconds": _ck("timeout_seconds"),
2957
+ "timeout_milliseconds": _ck("timeout_milliseconds"),
2958
+ "pseudo_header_order": _ck("pseudo_header_order"),
2959
+ "h3_pseudo_header_order": _ck("h3_pseudo_header_order"),
2960
+ "default_headers": _ck("default_headers"),
2961
+ "connect_headers": _ck("connect_headers"),
2962
+ "certificate_pinning_hosts": _ck("certificate_pinning_hosts"),
2963
+ "client_certificates": _ck("client_certificates"),
2964
+ "custom_tls_client": _ck("custom_tls_client"),
2965
+ })
2966
+ c_ck = _c_string(ffi, ck_hash)
2967
+ if c_ck != ffi.NULL:
2968
+ keep_alive.append(c_ck)
2969
+ opts.cache_key_hash = c_ck
2970
+
2821
2971
  opts.timeout_seconds = _val("timeout_seconds")
2822
2972
  opts.timeout_milliseconds = _val("timeout_milliseconds")
2823
2973
  opts.follow_redirects = _val("follow_redirects", True)
@@ -2906,54 +3056,6 @@ class AsyncSession:
2906
3056
  ctc_ptr = _build_custom_tls_client(ffi, ctc, keep_alive)
2907
3057
  opts.custom_tls_client = ctc_ptr
2908
3058
 
2909
- # Pre-compute cache key hash and attach to opts (avoids ~50 CGO calls on hit).
2910
- # Use kwargs.get() (non-destructive) so later _val() calls still find overrides.
2911
- def _ck(name): return kwargs.get(name, self._session.defaults.get(name))
2912
- def _ckb(name): v = kwargs.get(name, self._session.defaults.get(name)); return 1 if v else 0
2913
- ck_hash = _compute_cache_key_hash({
2914
- "client_identifier": _ck("client_identifier") or "",
2915
- "proxy": _ck("proxy") or "",
2916
- "server_name_overwrite": _ck("server_name_overwrite") or "",
2917
- "local_address": _ck("local_address") or "",
2918
- "insecure_skip_verify": _ckb("insecure_skip_verify"),
2919
- "force_http1": _ckb("force_http1"),
2920
- "with_random_tls_extension_order": _ckb("with_random_tls_extension_order"),
2921
- "with_protocol_racing": _ckb("with_protocol_racing"),
2922
- "max_idle_connections": _ck("max_idle_connections"),
2923
- "max_idle_connections_per_host": _ck("max_idle_connections_per_host"),
2924
- "max_connections_per_host": _ck("max_connections_per_host"),
2925
- "max_response_header_bytes": _ck("max_response_header_bytes"),
2926
- "write_buffer_size": _ck("write_buffer_size"),
2927
- "read_buffer_size": _ck("read_buffer_size"),
2928
- "idle_conn_timeout_seconds": _ck("idle_conn_timeout_seconds"),
2929
- "disable_keep_alives": _ckb("disable_keep_alives"),
2930
- "disable_compression": _ckb("disable_compression"),
2931
- "disable_http3": _ckb("disable_http3"),
2932
- "disable_ipv4": _ckb("disable_ipv4"),
2933
- "disable_ipv6": _ckb("disable_ipv6"),
2934
- "tcp_ttl": _ck("tcp_ttl"),
2935
- "tcp_window_size": _ck("tcp_window_size"),
2936
- "tcp_window_scale": _ck("tcp_window_scale"),
2937
- "tcp_mss": _ck("tcp_mss"),
2938
- "follow_redirects": _ckb("follow_redirects"),
2939
- "without_cookie_jar": _ckb("without_cookie_jar"),
2940
- "allow_empty_cookies": _ckb("allow_empty_cookies"),
2941
- "with_default_bad_pin_handler": _ckb("with_default_bad_pin_handler"),
2942
- "timeout_seconds": _ck("timeout_seconds"),
2943
- "timeout_milliseconds": _ck("timeout_milliseconds"),
2944
- "pseudo_header_order": _ck("pseudo_header_order"),
2945
- "h3_pseudo_header_order": _ck("h3_pseudo_header_order"),
2946
- "default_headers": _ck("default_headers"),
2947
- "connect_headers": _ck("connect_headers"),
2948
- "certificate_pinning_hosts": _ck("certificate_pinning_hosts"),
2949
- "client_certificates": _ck("client_certificates"),
2950
- "custom_tls_client": _ck("custom_tls_client"),
2951
- })
2952
- c_ck = _c_string(ffi, ck_hash)
2953
- if c_ck != ffi.NULL:
2954
- keep_alive.append(c_ck)
2955
- opts.cache_key_hash = c_ck
2956
-
2957
3059
  # ---- streaming fields (injected by stream_to_file) -----------------
2958
3060
  stream_path = kwargs.pop("_stream_output_path", ffi.NULL)
2959
3061
  stream_bs = kwargs.pop("_stream_output_block_size", 0)
@@ -3248,6 +3350,125 @@ class AsyncSession:
3248
3350
  async def patch(self, url: str, *, headers: Optional[Dict[str, str]] = None, body: Optional[bytes] = None, **kwargs: Any) -> Response:
3249
3351
  return await self.execute_request("PATCH", url, headers=headers, body=body, **kwargs)
3250
3352
 
3353
+ async def request(
3354
+ self,
3355
+ method: str,
3356
+ url: str,
3357
+ *,
3358
+ params: Optional[Dict[str, str]] = None,
3359
+ data: Union[bytes, str, Dict[str, str], None] = None,
3360
+ json: Any = None,
3361
+ headers: Optional[Dict[str, str]] = None,
3362
+ auth: Optional[Tuple[str, str]] = None,
3363
+ cookies: Optional[Dict[str, str]] = None,
3364
+ stream: Optional[bool] = None,
3365
+ cert: Optional[Union[str, Tuple[str, str]]] = None,
3366
+ timeout: Optional[int] = None,
3367
+ allow_redirects: Optional[bool] = None,
3368
+ proxies: Optional[Dict[str, str]] = None,
3369
+ verify: Optional[bool] = None,
3370
+ **kwargs: Any,
3371
+ ) -> Response:
3372
+ """``requests`` 兼容的异步 HTTP 请求方法。
3373
+
3374
+ ``requests``-compatible async HTTP request method.
3375
+
3376
+ :attr:`params` 自动拼接到 URL,:attr:`data` / :attr:`json` 自动编码请求体,
3377
+ :attr:`auth` 自动设置 ``Authorization`` 头,:attr:`cert` 自动读取文件并转为 mTLS 证书。
3378
+ 所有参数均可通过 Session 属性预设,也可单次请求覆盖。
3379
+ """
3380
+ if params:
3381
+ from urllib.parse import urlencode, urlparse, urlunparse
3382
+ parsed = urlparse(url)
3383
+ merged = dict(
3384
+ (k, v) for k, v in (p.split("=", 1) for p in parsed.query.split("&") if p)
3385
+ )
3386
+ merged.update(params)
3387
+ url = urlunparse(parsed._replace(
3388
+ query=urlencode([(k, v) for k, v in merged.items()])
3389
+ ))
3390
+ body = kwargs.pop("body", None)
3391
+ if body is None and data is not None:
3392
+ if isinstance(data, dict):
3393
+ from urllib.parse import urlencode
3394
+ body = urlencode(data).encode("utf-8")
3395
+ if headers is None:
3396
+ headers = {}
3397
+ if "Content-Type" not in {k.lower(): v for k, v in (headers or {}).items()}:
3398
+ headers = dict(headers or {})
3399
+ headers["Content-Type"] = "application/x-www-form-urlencoded"
3400
+ elif isinstance(data, str):
3401
+ body = data.encode("utf-8")
3402
+ else:
3403
+ body = data
3404
+ if json is not None:
3405
+ import json as _json
3406
+ body = _json.dumps(json, ensure_ascii=False).encode("utf-8")
3407
+ if headers is None:
3408
+ headers = {}
3409
+ if "Content-Type" not in {k.lower(): v for k, v in (headers or {}).items()}:
3410
+ headers = dict(headers or {})
3411
+ headers["Content-Type"] = "application/json"
3412
+ _auth = auth if auth is not None else self._session.defaults.get("auth")
3413
+ if _auth is not None:
3414
+ import base64
3415
+ user, pwd = _auth
3416
+ encoded = base64.b64encode(f"{user}:{pwd}".encode("utf-8")).decode("ascii")
3417
+ if headers is None:
3418
+ headers = {}
3419
+ headers = dict(headers or {})
3420
+ headers.setdefault("Authorization", f"Basic {encoded}")
3421
+ _cert = cert if cert is not None else self._session.defaults.get("cert")
3422
+ client_certificates = kwargs.pop("client_certificates", None)
3423
+ if client_certificates is None and _cert is not None:
3424
+ if isinstance(_cert, str):
3425
+ with open(_cert, "rb") as f:
3426
+ cert_bytes = f.read()
3427
+ client_certificates = [{"cert_pem": cert_bytes, "key_pem": cert_bytes}]
3428
+ elif isinstance(_cert, tuple) and len(_cert) == 2:
3429
+ with open(_cert[0], "rb") as f:
3430
+ cert_bytes = f.read()
3431
+ with open(_cert[1], "rb") as f:
3432
+ key_bytes = f.read()
3433
+ client_certificates = [{"cert_pem": cert_bytes, "key_pem": key_bytes}]
3434
+ _cookies = cookies if cookies is not None else kwargs.pop("request_cookies", None)
3435
+ kwargs.pop("request_cookies", None) # guard against duplicate kwarg in **kwargs
3436
+ _proxies = proxies
3437
+ if _proxies is not None:
3438
+ scheme = url.split(":", 1)[0].lower()
3439
+ proxy_url = _proxies.get(scheme) or _proxies.get("all") or next(
3440
+ iter(_proxies.values()), None
3441
+ )
3442
+ kwargs.setdefault("proxy", proxy_url)
3443
+ if allow_redirects is not None:
3444
+ kwargs.setdefault("follow_redirects", allow_redirects)
3445
+ if timeout is not None:
3446
+ kwargs.setdefault("timeout", timeout)
3447
+ if verify is not None:
3448
+ kwargs.setdefault("verify", verify)
3449
+ if stream is not None:
3450
+ kwargs.setdefault("stream", stream)
3451
+ return await self.execute_request(
3452
+ method, url,
3453
+ headers=headers,
3454
+ body=body,
3455
+ request_cookies=_cookies,
3456
+ client_certificates=client_certificates,
3457
+ **kwargs,
3458
+ )
3459
+
3460
+ async def options(self, url: str, **kwargs: Any) -> Response:
3461
+ """发送异步 HTTP OPTIONS 请求 / Send an async HTTP OPTIONS request."""
3462
+ return await self.request("OPTIONS", url, **kwargs)
3463
+
3464
+ def close(self) -> None:
3465
+ """关闭异步会话,释放 Go 客户端池中的空闲连接。
3466
+
3467
+ Close the async session and release idle connections in the Go client pool.
3468
+ """
3469
+ _, lib = _get_ffi()
3470
+ lib.ClearClientPool()
3471
+
3251
3472
  @staticmethod
3252
3473
  def clear_client_pool() -> None:
3253
3474
  """Close all idle connections in the global Go client pool.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tls-client-python
3
- Version: 1.15.0.4
3
+ Version: 1.15.1
4
4
  Summary: High-performance Python binding for bogdanfinn/tls-client via CFFI – zero-copy, panic-proof, full TLS fingerprint control
5
5
  Author: komAAmok
6
6
  License-Expression: MIT