2.3.0SessionOptions增加make_session()方法

This commit is contained in:
g1879 2023-02-23 00:11:34 +08:00
parent bccb20b84a
commit 29bbb7ea4c
6 changed files with 31 additions and 32 deletions

View File

@ -5,7 +5,10 @@
"""
from pathlib import Path
from DrissionPage.common.web import cookies_to_tuple
from requests import Session
from requests.structures import CaseInsensitiveDict
from DrissionPage.common.web import cookies_to_tuple, set_session_cookies
from .options_manage import OptionsManager
@ -375,6 +378,27 @@ class SessionOptions(object):
"""以字典形式返回本对象"""
return session_options_to_dict(self)
def make_session(self):
"""根据内在的配置生成Session对象"""
s = Session()
if self.headers:
s.headers = CaseInsensitiveDict(self.headers)
if self.cookies:
set_session_cookies(s, self.cookies)
if self.adapters:
for url, adapter in self.adapters:
s.mount(url, adapter)
attrs = ['auth', 'proxies', 'hooks', 'params', 'verify',
'cert', 'stream', 'trust_env', 'max_redirects']
for i in attrs:
attr = self.__getattribute__(i)
if attr:
s.__setattr__(i, attr)
return s
def session_options_to_dict(options):
"""把session配置对象转换为字典

View File

@ -6,6 +6,7 @@
from pathlib import Path
from typing import Any, Union, Tuple
from requests import Session
from requests.adapters import HTTPAdapter
from requests.auth import HTTPBasicAuth
from requests.cookies import RequestsCookieJar
@ -112,5 +113,7 @@ class SessionOptions(object):
def as_dict(self) -> dict: ...
def make_session(self) -> Session: ...
def session_options_to_dict(options: Union[dict, SessionOptions, None]) -> Union[dict, None]: ...

View File

@ -58,7 +58,7 @@ class SessionPage(BasePage):
def _create_session(self):
"""创建内建Session对象"""
if not self._session:
self._session = set_session(self._session_options)
self._session = self._session_options.make_session()
def __call__(self, loc_or_str, timeout=None):
"""在内部查找元素
@ -533,28 +533,3 @@ def set_charset(response) -> Response:
response.encoding = charset
return response
def set_session(opt):
"""根据传入配置对象创建Session对象
:param opt: SessionOptions对象
:return: Session
"""
s = Session()
if opt.headers:
s.headers = CaseInsensitiveDict(opt.headers)
if opt.cookies:
set_session_cookies(s, opt.cookies)
if opt.adapters:
for url, adapter in opt.adapters:
s.mount(url, adapter)
attrs = ['auth', 'proxies', 'hooks', 'params', 'verify',
'cert', 'stream', 'trust_env', 'max_redirects']
for i in attrs:
attr = opt.__getattribute__(i)
if attr:
s.__setattr__(i, attr)
return s

View File

@ -229,6 +229,3 @@ def check_headers(kwargs: Union[dict, CaseInsensitiveDict], headers: Union[dict,
def set_charset(response: Response) -> Response: ...
def set_session(opt: SessionOptions) -> Session: ...

View File

@ -2,7 +2,7 @@ requests
tldextract
lxml
cssselect
DownloadKit>=0.5.2
DownloadKit>=0.5.3
FlowViewer>=0.2.1
websocket-client
click

View File

@ -22,7 +22,7 @@ setup(
"lxml",
"tldextract",
"requests",
"DownloadKit>=0.5.2",
"DownloadKit>=0.5.3",
"FlowViewer",
"websocket-client",
'click~=8.1.3'