session

2023-05-16

class Session(SessionRedirectMixin):
    """A Requests session.

    Provides cookie persistence, connection-pooling, and configuration.

    Basic Usage::

      >>> import requests
      >>> s = requests.Session()
      >>> s.get('https://httpbin.org/get')
      <Response [200]>

    Or as a context manager::

      >>> with requests.Session() as s:
      >>>     s.get('https://httpbin.org/get')
      <Response [200]>
    """

    __attrs__ = [
        'headers', 'cookies', 'auth', 'proxies', 'hooks', 'params', 'verify',
        'cert', 'prefetch', 'adapters', 'stream', 'trust_env',
        'max_redirects',
    ]

    def __init__(self):

        #: A case-insensitive dictionary of headers to be sent on each
        #: :class:`Request <Request>` sent from this
        #: :class:`Session <Session>`.
        self.headers = default_headers()

        #: Default Authentication tuple or object to attach to
        #: :class:`Request <Request>`.
        self.auth = None

        #: Dictionary mapping protocol or protocol and host to the URL of the proxy
        #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to
        #: be used on each :class:`Request <Request>`.
        self.proxies = {}

        #: Event-handling hooks.
        self.hooks = default_hooks()

        #: Dictionary of querystring data to attach to each
        #: :class:`Request <Request>`. The dictionary values may be lists for
        #: representing multivalued query parameters.
        self.params = {}

        #: Stream response content default.
        self.stream = False

        #: SSL Verification default.
        self.verify = True

        #: SSL client certificate default, if String, path to ssl client
        #: cert file (.pem). If Tuple, ('cert', 'key') pair.
        self.cert = None

        #: Maximum number of redirects allowed. If the request exceeds this
        #: limit, a :class:`TooManyRedirects` exception is raised.
        #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is
        #: 30.
        self.max_redirects = DEFAULT_REDIRECT_LIMIT

        #: Trust environment settings for proxy configuration, default
        #: authentication and similar.
        self.trust_env = True

        #: A CookieJar containing all currently outstanding cookies set on this
        #: session. By default it is a
        #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but
        #: may be any other ``cookielib.CookieJar`` compatible object.
        self.cookies = cookiejar_from_dict({})

        # Default connection adapters.
        self.adapters = OrderedDict()
        self.mount('https://', HTTPAdapter())
        self.mount('http://', HTTPAdapter())

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.close()

    def prepare_request(self, request):
        """Constructs a :class:`PreparedRequest <PreparedRequest>` for
        transmission and returns it. The :class:`PreparedRequest` has settings
        merged from the :class:`Request <Request>` instance and those of the
        :class:`Session`.

        :param request: :class:`Request` instance to prepare with this
            session's settings.
        :rtype: requests.PreparedRequest
        """
        cookies = request.cookies or {}

        # Bootstrap CookieJar.
        if not isinstance(cookies, cookielib.CookieJar):
            cookies = cookiejar_from_dict(cookies)

        # Merge with session cookies
        merged_cookies = merge_cookies(
            merge_cookies(RequestsCookieJar(), self.cookies), cookies)

        # Set environment's basic authentication if not explicitly set.
        auth = request.auth
        if self.trust_env and not auth and not self.auth:
            auth = get_netrc_auth(request.url)

        p = PreparedRequest()
        p.prepare(
            method=request.method.upper(),
            url=request.url,
            files=request.files,
            data=request.data,
            json=request.json,
            headers=merge_setting(request.headers, self.headers, dict_class=CaseInsensitiveDict),
            params=merge_setting(request.params, self.params),
            auth=merge_setting(auth, self.auth),
            cookies=merged_cookies,
            hooks=merge_hooks(request.hooks, self.hooks),
        )
        return p

    def request(self, method, url,
            params=None, data=None, headers=None, cookies=None, files=None,
            auth=None, timeout=None, allow_redirects=True, proxies=None,
            hooks=None, stream=None, verify=None, cert=None, json=None):
        """Constructs a :class:`Request <Request>`, prepares it and sends it.
        Returns :class:`Response <Response>` object.

        :param method: method for the new :class:`Request` object.
        :param url: URL for the new :class:`Request` object.
        :param params: (optional) Dictionary or bytes to be sent in the query
            string for the :class:`Request`.
        :param data: (optional) Dictionary, list of tuples, bytes, or file-like
            object to send in the body of the :class:`Request`.
        :param json: (optional) json to send in the body of the
            :class:`Request`.
        :param headers: (optional) Dictionary of HTTP Headers to send with the
            :class:`Request`.
        :param cookies: (optional) Dict or CookieJar object to send with the
            :class:`Request`.
        :param files: (optional) Dictionary of ``'filename': file-like-objects``
            for multipart encoding upload.
        :param auth: (optional) Auth tuple or callable to enable
            Basic/Digest/Custom HTTP Auth.
        :param timeout: (optional) How long to wait for the server to send
            data before giving up, as a float, or a :ref:`(connect timeout,
            read timeout) <timeouts>` tuple.
        :type timeout: float or tuple
        :param allow_redirects: (optional) Set to True by default.
        :type allow_redirects: bool
        :param proxies: (optional) Dictionary mapping protocol or protocol and
            hostname to the URL of the proxy.
        :param stream: (optional) whether to immediately download the response
            content. Defaults to ``False``.
        :param verify: (optional) Either a boolean, in which case it controls whether we verify
            the server's TLS certificate, or a string, in which case it must be a path
            to a CA bundle to use. Defaults to ``True``.
        :param cert: (optional) if String, path to ssl client cert file (.pem).
            If Tuple, ('cert', 'key') pair.
        :rtype: requests.Response
        """
        # Create the Request.
        req = Request(
            method=method.upper(),
            url=url,
            headers=headers,
            files=files,
            data=data or {},
            json=json,
            params=params or {},
            auth=auth,
            cookies=cookies,
            hooks=hooks,
        )
        prep = self.prepare_request(req)

        proxies = proxies or {}

        settings = self.merge_environment_settings(
            prep.url, proxies, stream, verify, cert
        )

        # Send the request.
        send_kwargs = {
            'timeout': timeout,
            'allow_redirects': allow_redirects,
        }
        send_kwargs.update(settings)
        resp = self.send(prep, **send_kwargs)

        return resp

    def get(self, url, **kwargs):
        r"""Sends a GET request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        """

        kwargs.setdefault('allow_redirects', True)
        return self.request('GET', url, **kwargs)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

session 的相关文章

  • 查明具有特定 ID 的会话是否已过期

    我正在创建一个上传功能 将用户上传的文件存储在服务器上 并以用户的会话 ID 作为名称 现在 我只想将此文件保留在服务器上 直到该会话处于活动状态 所以 我的问题是 如何根据会话 ID 确定会话是活动的还是过期的 以便在后一种情况下我可以安
  • PHP中如何有效防止跨站请求伪造(CSRF)

    我正在努力阻止CSRF https www owasp org index php Cross Site Request Forgery CSRF in php questions tagged php通过以下方式 A SESSION to
  • Roslyn,通过 hostObject 传递值

    我正在尝试通过 hostObject 发送一个类 但显然它不想工作 using Roslyn Compilers using Roslyn Compilers CSharp using Roslyn Scripting using Rosl
  • 使用 python3 和请求登录 Twitter

    我正在开发一个项目 要求使用用户名和密码登录网站 我必须在 python 中执行此操作 然后才能访问只有登录人员才能访问的网站部分 我尝试了几种编码变体来执行此操作 但无法成功登录然而 这是我的编码 登录它的功能 def 会话2 url r
  • 测试 CodeIgniter 会话变量的正确方法是什么?

    获取以下代码片段 测试确保会话变量不为空的最佳方法是什么 如果稍后在我的脚本中 我调用以下内容 第一个打印正确 但在第二个我收到消息 未定义的变量 已登录 我尝试过使用 empty and isset 但两者均未成功 我还尝试使用向后执行
  • 没有适用于机器人的 Laravel 会话

    我在大型 Laravel 项目和 Redis 存储方面遇到问题 我们将会话存储在 Redis 中 我们已经有 28GB 的 RAM 然而 它的运行速度仍然相对较快 达到了极限 因为我们有来自搜索引擎机器人的大量点击 每天超过 250 000
  • PHP 自定义会话处理程序问题 (PHP 7.1)

    我刚刚在计算机上从 PHP 7 0 迁移到 PHP 7 1 当前版本的 WAMP 的全新 全新安装 它似乎破坏了自定义会话处理程序中的某些内容 该处理程序应该将会话保存到数据库而不是使用文件系统 自定义处理程序类是 class db ses
  • 适用于移动应用程序的 Rails REST API。会议

    我正在创建一个移动应用程序 该应用程序拥有用户并与后端的自定义 Rails REST API 进行通信 我应该在登录时创建会话吗 或者我应该在每个请求中发送用户名和密码 如果会议是可行的方法 那么通常是如何实施的 只需生成令牌 并使用它们来
  • PHP:会话.auto_start

    我在同一台服务器上有两个项目 它们的设置在 session auto start 中冲突 相关post https stackoverflow com questions 1378324 php setting variables in i
  • NHibernate Session.Flush & Evict 与 Clear

    在一个测试中 我想要持久化一个对象 然后通过从数据库 而不是会话 获取它来证明它是持久化的 我注意到以下内容没有区别 save it session Clear fetch it or save it session Flush sessi
  • Codeigniter:用户会话不断过期

    我正在使用 CodeIgniter 但在会话方面遇到了一个小问题 我已将 config php 中的 sess expiration 设置为 0 以便用户会话永远不会过期 但用户 甚至我自己 仍然偶尔会被踢出并要求再次登录 顺便说一句 我将
  • 随机 IIS 会话超时

    我有一个非常奇怪的问题 我正在寻求任何建议 我有一个运行在 IIS 6 上的 ASP NET 网站 它在大多数情况下运行良好 但是 会话似乎是随机清除的 因此 如果我登录 单击周围 我就会被随机启动 有时是在 30 秒 4 次点击之后 有时
  • viewExpiredException JSF [重复]

    这个问题在这里已经有答案了 为了处理 JSF 中的 viewExpiredException 我编写了代码
  • 从自定义设置会话文件夹中删除旧会话文件?

    使用 PHP 如果我设置自定义会话文件夹来存储会话文件 我必须做什么才能确保旧会话文件最终被删除 有没有办法让 Apache 或 PHP 为我处理这个问题 或者我需要设置一些东西来自己清理这个文件夹 非常感谢有关此主题的任何信息 我目前正在
  • 在 Laravel 中获取身份验证用户 ID

    如果用户登录 Laravel 5 1 我们可以访问用户 ID Auth user gt id 在我以前的应用程序 不是 laravel 中 当用户登录时 我正在为 userid 注册一个会话 我正在检查 SESSION user id 是否
  • Symfony2:间歇性高响应时间/缓慢 SessionHandlerProxy::read() 完成

    我看到来自 Symfony2 会话管理器组件的非常奇怪的行为 特别是 SessionHandlerProxy read 函数在我的生产环境中有时会非常慢 Symfony Component HttpFoundation Session St
  • 处理 PHP 中的会话劫持

    阅读了 Stackoverflow 上有关会话劫持的许多问题 我发现验证用户会话的唯一 解决方案 是检查用户代理 这是一个薄弱的保护层 我什至懒得去检查实施它 所以 我想知道你们实施了哪些解决方案 您是否使用 PHP 的本机会话或者是否有更
  • 一键提交多个表单

    我在用 SESSION为我的网上商店动态创建表单 这些表单包含客户想要的产品的自定义信息 这是布局 Page1 客户填写的表格如下所示
  • OWIN中间件可以使用http会话吗?

    我有一些为 ASP NET 和 SignalR 复制的代码 我决定将其重写为 OWIN 中间件以删除这些重复 一旦我运行它 我注意到HttpContext Current Session为空 并且我没有看到任何会话对象IOwinContex
  • NHibernate、数据绑定到 DataGridView、延迟加载和会话管理 - 需要建议

    我的主应用程序窗体 WinForms 有一个 DataGridView 它使用 DataBinding 和 Fluent NHibernate 显示 SQLite 数据库中的数据 该表单在应用程序运行的整个过程中都是打开的 出于性能原因 我

随机推荐