3
3
import uuid
4
4
import warnings
5
5
from collections .abc import Mapping
6
- from http .cookiejar import CookieJar
6
+ from http .cookiejar import CookieJar , Cookie
7
7
from urllib .parse import quote_plus , urlencode as _urlencode
8
8
9
9
from twisted .internet .interfaces import IProtocol
30
30
from treq .auth import add_auth
31
31
from treq import multipart
32
32
from treq .response import _Response
33
- from requests .cookies import cookiejar_from_dict , merge_cookies
33
+ from requests .cookies import merge_cookies
34
34
35
35
36
36
_NOTHING = object ()
@@ -43,6 +43,45 @@ def urlencode(query, doseq):
43
43
return s
44
44
45
45
46
+ def _scoped_cookiejar_from_dict (url_object , cookie_dict ):
47
+ """
48
+ Create a CookieJar from a dictionary whose cookies are all scoped to the
49
+ given URL's origin.
50
+
51
+ @note: This does not scope the cookies to any particular path, only the
52
+ host, port, and scheme of the given URL.
53
+ """
54
+ cookie_jar = CookieJar ()
55
+ if cookie_dict is None :
56
+ return cookie_jar
57
+ for k , v in cookie_dict .items ():
58
+ cookie_jar .set_cookie (
59
+ Cookie (
60
+ version = 0 ,
61
+ name = k ,
62
+ value = v ,
63
+ domain = url_object .host ,
64
+ port = str (url_object .port ),
65
+ path = "" ,
66
+ secure = (url_object .scheme == 'https' ),
67
+ expires = None ,
68
+ discard = False ,
69
+ comment = None ,
70
+ comment_url = None ,
71
+ rfc2109 = False ,
72
+ port_specified = (
73
+ not (url_object .scheme == "https" and url_object .port == 443 )
74
+ or (url_object .scheme == "http" and url_object .port == 80 )
75
+ ),
76
+ path_specified = False ,
77
+ domain_specified = False ,
78
+ domain_initial_dot = False ,
79
+ rest = [],
80
+ )
81
+ )
82
+ return cookie_jar
83
+
84
+
46
85
class _BodyBufferingProtocol (proxyForInterface (IProtocol )):
47
86
def __init__ (self , original , buffer , finished ):
48
87
self .original = original
@@ -98,7 +137,9 @@ class HTTPClient:
98
137
def __init__ (self , agent , cookiejar = None ,
99
138
data_to_body_producer = IBodyProducer ):
100
139
self ._agent = agent
101
- self ._cookiejar = cookiejar or cookiejar_from_dict ({})
140
+ if cookiejar is None :
141
+ cookiejar = CookieJar ()
142
+ self ._cookiejar = cookiejar
102
143
self ._data_to_body_producer = data_to_body_producer
103
144
104
145
def get (self , url , ** kwargs ):
@@ -195,7 +236,7 @@ def request(
195
236
headers .setRawHeaders (b'Content-Type' , [contentType ])
196
237
197
238
if not isinstance (cookies , CookieJar ):
198
- cookies = cookiejar_from_dict ( cookies )
239
+ cookies = _scoped_cookiejar_from_dict ( parsed_url , cookies )
199
240
200
241
cookies = merge_cookies (self ._cookiejar , cookies )
201
242
wrapped_agent = CookieAgent (self ._agent , cookies )
0 commit comments