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 的相关文章

  • 服务器上的 Rails 会话

    我想让一些 Rails 应用程序在不同的服务器上共享同一个会话 我可以在同一服务器内完成此操作 但不知道是否可以在不同服务器上共享 有人已经做过或者知道怎么做吗 Thanks Use the 数据库会话存储 https github com
  • 如何处理 AJAX 请求中的会话超时

    我相信你们都熟悉使用 AJAX 的投票系统 嗯 看那边 我有类似的东西 当你投票赞成或反对时 它使用 AJAX 从 votes php 请求新值 问题是我正在使用会话来获取用户 ID 因此一个人只能投票一次 如果他们在页面上坐了一个小时然后
  • ASP.NET:如何删除所有用户的所有会话变量?

    我们有 ASP NET 应用程序 想要删除所有用户的所有会话中的所有会话变量 我的意思是不要仅使用以下命令从当前会话中删除会话变量 Session Clear or Session Abandon 我们还需要清除其他用户会话中的会话变量吗
  • MySQL 概念:会话与连接

    我对 MySQL 的概念有点困惑 会话与连接 当谈论连接到 MySQL 时 我们使用连接术语 连接池等 然而在 MySQL 在线文档中 http dev mysql com doc refman 4 1 en server system v
  • 由于缺少会话而在 Next.js 中使用 Next-Auth 进行重定向时,如何显示 Toast 通知? [复制]

    这个问题在这里已经有答案了 例如 假设我有一个名为internal tsx 的页面 其中包含 export const getServerSideProps GetServerSideProps async ctx gt const ses
  • ASP.NET 会话状态服务器与 InProc 会话

    运行会话状态服务器而不是 InProc 的开销性能损失是多少 重要吗 我知道您可以使用状态服务器重新启动 w3wp 并保留所有会话状态 这是相对于 InProc 的唯一优势吗 这取决于您的部署计划 在单个服务器上 损失很小 但好处同样有限
  • PHP中如何有效防止跨站请求伪造(CSRF)

    我正在努力阻止CSRF https www owasp org index php Cross Site Request Forgery CSRF in php questions tagged php通过以下方式 A SESSION to
  • 修改不同Django用户的会话数据

    这可能不可能 但是当某些情况发生时 我想修改某些登录用户的会话数据 标记一些额外的逻辑需要在下次加载页面时运行 有没有办法通过用户 ID 访问用户的会话 tldr Query Session模型 然后通过修改匹配会话SessionStore
  • PHP7.1上读取会话数据失败

    分享一个我遇到的问题 现已解决 在我的开发机器上 我使用 PHP 运行 IIS 我升级到 PHP7 突然我的代码不再工作 返回此错误 session start 读取会话数据失败 用户 路径 C WINDOWS temp 看起来像是权限问题
  • 我可以在 php 中的 SESSION 数组上使用 array_push 吗?

    我有一个想要在多个页面上使用的数组 因此我将其设为 SESSION 数组 我想添加一系列名称 然后在另一个页面上 我希望能够使用 foreach 循环来回显该数组中的所有名称 这是会议 SESSION names 我想使用 array pu
  • 当请求来自网络服务器而不是网络浏览器时,HTTPSession 的创建如何工作?

    我有一个非常基本的问题 HTTPSession 的创建是如何工作的 我知道你们会因为我把这个问题视为类似的问题而解雇我 存在问题 但是我问这个问题是有原因的 我知道 httpsession 是 Web 浏览器所独有的 当我们第一次执行 Ht
  • 会话劫持和 PHP

    让我们只考虑服务器对用户的信任 会话固定 为了避免我使用的固定session regenerate id 仅在身份验证中 login php 会话侧劫持 整个站点的 SSL 加密 我安全吗 阅读 OWASPA3 破坏的身份验证和会话管理 h
  • PHP:会话.auto_start

    我在同一台服务器上有两个项目 它们的设置在 session auto start 中冲突 相关post https stackoverflow com questions 1378324 php setting variables in i
  • Magento 外部登录不会创建会话 cookie

    我正在尝试从外部站点替换 Magento 的相当笨拙的 ajax 登录 该网站使用 Magento 作为商店 站点和 magento 商店都有自己的登录信息 因此当用户登录时 两者同步非常重要 这是通过每次页面重新加载时进行 ajax 调用
  • 设计对多个并发会话的支持

    我使用 Rails 3 2 11 和 Devise 2 2 3 作为订阅服务应用程序 我从另一位不再可用的开发人员那里继承了该应用程序 我是 Rails 和 Devise 的新手 我想要允许单个用户 电子邮件 拥有多个会话到同一个应用程序
  • NHibernate Session.Flush & Evict 与 Clear

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

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

    我知道这个主题已经被讨论了很多 但我相信我已经找到了它的一个新变体 我有一个 Rails 4 应用程序 它是从 Rails 3 升级的 并且具有rails ujs and csrf meta tags设置正确 一旦root url在浏览器中
  • Rails 和 Authlogic:每个用户只允许一个会话?

    有没有办法限制 Ruby on Rails 应用程序中的会话数量 我使用 Authlogic 进行身份验证 我希望每个用户帐户只允许 1 个会话 当同一用户登录另一台计算机时 先前的会话应该过期 失效 我正在考虑将会话数据存储在数据库中 然
  • 从自定义设置会话文件夹中删除旧会话文件?

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

随机推荐