本文整理汇总了Python中http.cookiejar.CookieJar.set_cookie方法的典型用法代码示例。如果您正苦于以下问题:Python CookieJar.set_cookie方法的具体用法?Python CookieJar.set_cookie怎么用?Python CookieJar.set_cookie使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类http.cookiejar.CookieJar
的用法示例。
在下文中一共展示了CookieJar.set_cookie方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _getCookies
# 需要导入模块: from http.cookiejar import CookieJar [as 别名]
# 或者: from http.cookiejar.CookieJar import set_cookie [as 别名]
def _getCookies(headers):
cj = CookieJar()
cookies = headers.split(',')
for cookie in cookies:
attrs = cookie.split(';')
cookieNameValue = name = attrs[0].strip().split('=')
pathNameValue = name = attrs[1].strip().split('=')
ck = Cookie(version=1, name=cookieNameValue[0],
value=cookieNameValue[1],
port=443,
port_specified=False,
domain=swaDomain,
domain_specified=True,
domain_initial_dot=False,
path=pathNameValue[1],
path_specified=True,
secure=True,
expires=None,
discard=True,
comment=None,
comment_url=None,
rest={'HttpOnly': None},
rfc2109=False)
cj.set_cookie(ck)
return cj
示例2: enviaPeticion
# 需要导入模块: from http.cookiejar import CookieJar [as 别名]
# 或者: from http.cookiejar.CookieJar import set_cookie [as 别名]
def enviaPeticion(url, dominio, ruta, cookieDicc={"TESTID": "set"}):
try:
# Empaquetador de cookies.
jar = CookieJar()
# Genera un objeto request para posterior peticion.
peticion = urllib.request.Request(url=url)
# crearCookie to generate a cookie and add it to the cookie jar.
for key, item in cookieDicc.items():
jar.set_cookie(crearCookie(key, item, dominio, ruta))
# print(crearCookie(key, item))
jar.add_cookie_header(peticion)
# Generar peticion.
edmundoDantes = urllib.request.build_opener()
abreteSesamo = edmundoDantes.open(peticion)
RiquezaYVenganza = verificacionAcceso(abreteSesamo)
if RiquezaYVenganza:
print( "Busca tu propio Arbol")
else:
print( "!(Busca tu propio arbol)")
return RiquezaYVenganza
except urllib.error.HTTPError as err:
print("Pagina fuera de servicio")
return "Pagina fuera de servicio"
示例3: dict_2_cookiejar
# 需要导入模块: from http.cookiejar import CookieJar [as 别名]
# 或者: from http.cookiejar.CookieJar import set_cookie [as 别名]
def dict_2_cookiejar(d):
cj = CookieJar()
for c in d:
ck = Cookie(
name=c["name"],
value=urllib.parse.unquote(c["value"]),
domain=c["domain"],
path=c["path"],
secure=c["secure"],
rest={"HttpOnly": c["httponly"]},
version=0,
port=None,
port_specified=False,
domain_specified=False,
domain_initial_dot=False,
path_specified=True,
expires=None,
discard=True,
comment=None,
comment_url=None,
rfc2109=False,
)
cj.set_cookie(ck)
return cj
示例4: BuiltinBrowser
# 需要导入模块: from http.cookiejar import CookieJar [as 别名]
# 或者: from http.cookiejar.CookieJar import set_cookie [as 别名]
class BuiltinBrowser(BaseBrowser):
def __init__(self, base_url=None):
base_url = get_default_workflowy_url(base_url)
super().__init__(base_url)
self.cookie_jar = CookieJar()
self.opener = build_opener(HTTPCookieProcessor(self.cookie_jar))
def open(self, url, *, _raw=False, _query=None, **kwargs):
full_url = urljoin(self.base_url, url)
if _query is not None:
full_url += "?" + urlencode(_query)
data = urlencode(kwargs).encode()
headers = {
"Content-Type" : "application/x-www-form-urlencoded",
}
req = Request(full_url, data, headers)
res = self.opener.open(req)
with closing(res) as fp:
content = fp.read()
content = content.decode()
if not _raw:
# TODO: must not raise 404 error
content = json.loads(content)
return res, content
def set_cookie(self, name, value):
url = urlparse(self.base_url)
cookie = Cookie(
version=0,
name=name,
value=value,
port=None,
port_specified=False,
domain=url.netloc,
domain_specified=False,
domain_initial_dot=False,
path=url.path,
path_specified=True,
secure=False,
expires=sys.maxsize,
discard=False,
comment=None,
comment_url=None,
rest={},
rfc2109=False,
)
self.cookie_jar.set_cookie(cookie)
示例5: cookiejar_from_dict
# 需要导入模块: from http.cookiejar import CookieJar [as 别名]
# 或者: from http.cookiejar.CookieJar import set_cookie [as 别名]
def cookiejar_from_dict(cookie_dict, cookiejar=None):
"""Returns a CookieJar from a key/value dictionary.
:param cookie_dict: Dict of key/values to insert into CookieJar.
"""
if not isinstance(cookie_dict, CookieJar):
if cookiejar is None:
cookiejar = CookieJar()
if cookie_dict is not None:
for name in cookie_dict:
cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))
return cookiejar
else:
return cookie_dict
示例6: set_cookie
# 需要导入模块: from http.cookiejar import CookieJar [as 别名]
# 或者: from http.cookiejar.CookieJar import set_cookie [as 别名]
def set_cookie(self, cookie):
if cookie.discard:
CookieJar.set_cookie(self, cookie)
return
def set_cookie(cur):
# XXX
# is this RFC 2965-correct?
# could this do an UPDATE instead?
row = self._row_from_cookie(cookie, cur)
name, unused, domain, path = row[1:5]
cur.execute("""\
DELETE FROM moz_cookies WHERE host = ? AND path = ? AND name = ?""",
(domain, path, name))
cur.execute("""\
INSERT INTO moz_cookies VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
""", row)
self._transaction(set_cookie)
示例7: testCookieAdapters
# 需要导入模块: from http.cookiejar import CookieJar [as 别名]
# 或者: from http.cookiejar.CookieJar import set_cookie [as 别名]
def testCookieAdapters(self):
jar = CookieJar(policy=None) # DefaultCookiePolicy())
# set a cookie
res = Response()
tstval = str(uuid.uuid4())
res.set_cookie("a-cookie", tstval, domain="example.com")
cookies = jar.make_cookies(filters.ResponseCookieAdapter(res), Request.blank("http://example.com"))
for c in cookies:
jar.set_cookie(c)
self.assert_(len(jar), ("where's my cookies?"))
self.assert_("a-cookie" in [c.name for c in jar], "seriously, where's my cookie")
# now put the header on the request please
request = Request.blank("http://example.com")
self.assert_(".example.com" in jar._cookies.keys(), jar._cookies.keys())
jar.add_cookie_header(filters.RequestCookieAdapter(request))
self.assert_("Cookie" in request.headers, (str(request), "Y NO COOKIES?"))
示例8: get
# 需要导入模块: from http.cookiejar import CookieJar [as 别名]
# 或者: from http.cookiejar.CookieJar import set_cookie [as 别名]
def get(self, options, url):
cj = CookieJar()
match = re.search(".*video/([0-9]+)", url)
if not match:
log.error("Can't find video file")
sys.exit(2)
video_id = match.group(1)
if options.username and options.password:
#bogus
cc = Cookie(None, 'asdf', None, '80', '80', 'www.kanal5play.se', None, None, '/', None, False, False, 'TestCookie', None, None, None)
cj.set_cookie(cc)
#get session cookie
data = get_http_data("http://www.kanal5play.se/", cookiejar=cj)
authurl = "https://kanal5swe.appspot.com/api/user/login?callback=jQuery171029989&email=%s&password=%s&_=136250" % (options.username, options.password)
data = get_http_data(authurl)
match = re.search("({.*})\);", data)
jsondata = json.loads(match.group(1))
if jsondata["success"] == False:
log.error(jsondata["message"])
sys.exit(2)
authToken = jsondata["userData"]["auth"]
cc = Cookie(version=0, name='authToken',
value=authToken,
port=None, port_specified=False,
domain='www.kanal5play.se',
domain_specified=True,
domain_initial_dot=True, path='/',
path_specified=True, secure=False,
expires=None, discard=True, comment=None,
comment_url=None, rest={'HttpOnly': None})
cj.set_cookie(cc)
format = "FLASH"
if options.hls:
format = "IPHONE"
url = "http://www.kanal5play.se/api/getVideo?format=%s&videoId=%s" % (format, video_id)
data = json.loads(get_http_data(url, cookiejar=cj))
options.live = data["isLive"]
if data["hasSubtitle"]:
subtitle = "http://www.kanal5play.se/api/subtitles/%s" % video_id
if options.hls:
url = data["streams"][0]["source"]
baseurl = url[0:url.rfind("/")]
if data["streams"][0]["drmProtected"]:
log.error("We cant download drm files for this site.")
sys.exit(2)
download_hls(options, url, baseurl)
else:
steambaseurl = data["streamBaseUrl"]
streams = {}
for i in data["streams"]:
stream = {}
stream["source"] = i["source"]
streams[int(i["bitrate"])] = stream
test = select_quality(options, streams)
filename = test["source"]
match = re.search("^(.*):", filename)
options.other = "-W %s -y %s " % ("http://www.kanal5play.se/flash/K5StandardPlayer.swf", filename)
download_rtmp(options, steambaseurl)
if options.subtitle:
if options.output != "-":
data = get_http_data(subtitle, cookiejar=cj)
subtitle_json(options, data)
示例9: pyGoogleTrendsCsvDownloader
# 需要导入模块: from http.cookiejar import CookieJar [as 别名]
# 或者: from http.cookiejar.CookieJar import set_cookie [as 别名]
class pyGoogleTrendsCsvDownloader(object):
'''
Google Trends Downloader.
Recommended usage:
from pyGoogleTrendsCsvDownloader import pyGoogleTrendsCsvDownloader
r = pyGoogleTrendsCsvDownloader(username, password)
r.get_csv_data(cat='0-958', geo='US-ME-500')
'''
def __init__(self, username, password, proxy=None):
'''
Provide login and password to be used to connect to Google Trends
All immutable system variables are also defined here
'''
# The amount of time (in secs) that the script should wait before making a request.
# This can be used to throttle the downloading speed to avoid hitting servers too hard.
# It is further randomized.
self.download_delay = 2
self.service = "trendspro"
self.url_service = "http://www.google.com/trends/"
self.url_download = 'https://www.google.com/trends/trendsReport?'
self.login_params = {}
# These headers are necessary, otherwise Google will flag the request at your account level
self.headers = [('User-Agent', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36'),
("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"),
("Accept-Language", "en-gb,en;q=0.8"),
("Accept-Encoding", "gzip,deflate,sdch"),
("referer", "https://www.google.com/trends/explore"),
("pragma", "no-cache"),
("cache-control", "no-cache"),
]
self.url_login = 'https://accounts.google.com/ServiceLogin?service='+self.service+'&passive=1209600&continue='+self.url_service+'&followup='+self.url_service
self.url_authenticate = 'https://accounts.google.com/accounts/ServiceLoginAuth'
self.proxy = proxy
self._authenticate(username, password)
def _authenticate(self, username, password):
'''
Authenticate to Google:
1 - make a GET request to the Login webpage so we can get the login form
2 - make a POST request with email, password and login form input values
'''
# Make sure we get CSV results in English
ck1 = Cookie(version=0, name='I4SUserLocale', value='en_US', port=None, port_specified=False, domain='.google.com', domain_specified=False,domain_initial_dot=False, path='', path_specified=False, secure=False, expires=None, discard=False, comment=None, comment_url=None, rest=None)
# This cookie is now mandatory
# Not sure what the value represents but too many queries from the same value
# lead to a Quota Exceeded error.
# random_six_char = ''.join(random.choice('0123456789abcdef') for n in xrange(6))
ck2 = Cookie(version=0, name='PREF', value='0000', port=None, port_specified=False, domain='.google.com', domain_specified=False,domain_initial_dot=False, path='', path_specified=False, secure=False, expires=None, discard=False, comment=None, comment_url=None, rest=None)
self.cj = CookieJar()
self.cj.set_cookie(ck1)
self.cj.set_cookie(ck2)
if not self.proxy:
self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cj))
else:
proxy = urllib.request.ProxyHandler({'http': self.proxy,
'https': self.proxy})
self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cj), proxy)
self.opener.addheaders = self.headers
# Get all of the login form input values
find_inputs = etree.XPath("//form[@id='gaia_loginform']//input")
resp = self.opener.open(self.url_login)
data = self.read_gzipped_response(resp).decode()
try:
xmlTree = etree.fromstring(data, parser=html.HTMLParser(recover=True, remove_comments=True))
for input in find_inputs(xmlTree):
name = input.get('name')
if name:
name = name.encode('utf8')
value = input.get('value', '').encode('utf8')
self.login_params[name] = value
except:
raise AuthFailedException(("Exception while parsing: %s\n" % traceback.format_exc()))
self.login_params["Email".encode('utf8')] = username.encode('utf8')
self.login_params["Passwd".encode('utf8')] = password.encode('utf8')
params = urllib.parse.urlencode(self.login_params)
auth_resp = self.opener.open(self.url_authenticate, params.encode())
# Testing whether Authentication was a success
# I noticed that a correct auth sets a few cookies
if not self.is_authentication_successfull(auth_resp):
raise AuthFailedException('Warning: Authentication failed for user %s' % username)
def is_authentication_successfull(self, response):
'''
Arbitrary way of us knowing whether the authentication succeeded or not:
we look for a SSID cookie-set header value.
I noticed that the 4 mandatory cookies were:
#.........这里部分代码省略.........
示例10: Swedbank
# 需要导入模块: from http.cookiejar import CookieJar [as 别名]
# 或者: from http.cookiejar.CookieJar import set_cookie [as 别名]
class Swedbank(object):
BANKS = {
SWEDBANK: {
"id": "HithYAGrzi8fu73j",
"u-a": "SwedbankMOBPrivateIOS/3.9.0_(iOS;_8.0.2)_Apple/iPhone5,2"
},
SPARBANKEN: {
"id": "9iZSu74jfDFaTdPd",
"u-a": "SavingbankMOBPrivateIOS/3.9.0_(iOS;_8.0.2)_Apple/iPhone5,2"
},
SWEDBANK_UNG: {
"id": "IV4Wrt2VZtyYjfpW",
"u-a": "SwedbankMOBYouthIOS/1.6.0_(iOS;_8.0.2)_Apple/iPhone5,2"
},
SPARBANKEN_UNG: {
"id": "BrGkZQR89rEbFwnj",
"u-a": "SavingbankMOBYouthIOS/1.6.0_(iOS;_8.0.2)_Apple/iPhone5,2"
},
SWEDBANK_FORETAG: {
"id": "v0RVbFGKMXz7U4Eb",
"u-a": "SwedbankMOBCorporateIOS/1.5.0_(iOS;_8.0.2)_Apple/iPhone5,2"
},
SPARBANKEN_FORETAG: {
"id": "JPf1VxiskNdFSclr",
"u-a": "SavingbankMOBCorporateIOS/1.5.0_(iOS;_8.0.2)_Apple/iPhone5,2"
}
}
def __init__(self, username, password, bank=SWEDBANK):
""" Set default stuff """
self.data = ""
self.pch = None
self.authkey = None
self.cj = CookieJar()
self.profile = None
self.account = None
self.useragent = None
self.bankid = None
self.login(username, password, bank)
def get_authkey(self):
if self.authkey is None:
data = "%s:%s" % (self.bankid, uuid.uuid4())
self.authkey = base64.b64encode(data.encode("utf-8")).decode(
"utf-8")
return self.authkey
def get_dsid(self):
data = "%s%s" % (random.randint(0, 99999), random.randint(0, 99999))
hashvalue = hashlib.sha1(data.encode("utf-8")).hexdigest()[:8]
dsid = "%s%s" % (hashvalue[:4], hashvalue[4:].upper())
random.shuffle(list(dsid))
return ''.join(dsid)
def request(self, url, post=None, method="GET"):
""" Make the request"""
dsid = self.get_dsid()
baseurl = "https://auth.api.swedbank.se/TDE_DAP_Portal_REST_WEB/api/v1/%s?dsid=%s" % (
url, dsid)
if self.pch is None:
self.pch = build_opener(HTTPCookieProcessor(self.cj))
if post:
post = bytearray(post, "utf-8")
request = Request(baseurl, data=post)
request.add_header("Content-Type", "application/json")
else:
request = Request(baseurl)
request.add_header("User-Agent", self.useragent)
request.add_header("Authorization", self.get_authkey())
request.add_header("Accept", "*/*")
request.add_header("Accept-Language", "sv-se")
request.add_header("Connection", "keep-alive")
request.add_header("Proxy-Connection", "keep-alive")
self.cj.set_cookie(
Cookie(version=0, name='dsid', value=dsid, port=None,
port_specified=False, domain='.api.swedbank.se',
domain_specified=False, domain_initial_dot=False,
path='/',
path_specified=True, secure=False, expires=None,
discard=True, comment=None, comment_url=None,
rest={'HttpsOnly': None}, rfc2109=False))
request.get_method = lambda: method
tmp = self.pch.open(request)
self.data = tmp.read().decode("utf8")
def login(self, user, passwd, bank):
""" Login """
logger.info("login...")
if bank not in self.BANKS:
logger.error("Can't find that bank.")
return False
self.useragent = self.BANKS[bank]["u-a"]
self.bankid = self.BANKS[bank]["id"]
login = json.dumps(
{"userId": user, "password": passwd, "useEasyLogin": False,
"generateEasyLoginId": False})
try:
#.........这里部分代码省略.........
示例11: to_pycookiejar
# 需要导入模块: from http.cookiejar import CookieJar [as 别名]
# 或者: from http.cookiejar.CookieJar import set_cookie [as 别名]
def to_pycookiejar(QtCookiejar):
cj = CookieJar()
for c in QtCookiejar.allCookies():
cj.set_cookie(to_py_cookie(c))
return cj
示例12: Response
# 需要导入模块: from http.cookiejar import CookieJar [as 别名]
# 或者: from http.cookiejar.CookieJar import set_cookie [as 别名]
#.........这里部分代码省略.........
block_headers = []
for header in raw_block:
if not header:
continue
elif not header.startswith("HTTP"):
field, value = [u.strip() for u in header.split(":", 1)]
if field.startswith("Location"):
# maybe not good
if not value.startswith("http"):
value = urljoin(self.url, value)
self._history.append(value)
if value[:1] == value[-1:] == '"':
value = value[1:-1] # strip "
block_headers.append((field, value.strip()))
elif header.startswith("HTTP"):
# extract version, code, message from first header
try:
version, code, message = HTTP_GENERAL_RESPONSE_HEADER.findall(header)[0]
except Exception as e:
logger.warn(e)
continue
else:
block_headers.append((version, code, message))
else:
# raise ValueError("Wrong header field")
pass
return block_headers
raw_headers = self._headers_output.getvalue()
for raw_block in self._split_headers_blocks(raw_headers):
block = parse_header_block(raw_block)
self._headers_history.append(block)
last_header = self._headers_history[-1]
self._headers = CaseInsensitiveDict(last_header[1:])
if not self._history:
self._history.append(self.url)
def parse_cookies(self):
from http.cookies import SimpleCookie, CookieError
if not self._headers_history:
self._parse_headers_raw()
# Get cookies from endpoint
cookies = []
for header in chain(*self._headers_history):
if len(header) > 2:
continue
key, value = header[0], header[1]
if key.lower().startswith("set-cookie"):
try:
cookie = SimpleCookie()
cookie.load(value)
cookies.extend(list(cookie.values()))
# update cookie jar
for morsel in list(cookie.values()):
if isinstance(self._cookies_jar, CookieJar):
self._cookies_jar.set_cookie(morsel_to_cookie(morsel))
except CookieError as e:
logger.warn(e)
self._cookies = dict([(cookie.key, cookie.value) for cookie in cookies])
return self._cookies
@property
def headers(self):
"""Returns response headers
"""
if not self._headers:
self._parse_headers_raw()
return self._headers
@property
def cookies(self):
"""Returns list of BaseCookie object
All cookies in list are ``Cookie.Morsel`` instance
:return self._cookies: cookies list
"""
if not self._cookies:
self.parse_cookies()
return self._cookies
@property
def history(self):
"""Returns redirects history list
:return: list of `Response` objects
"""
if not self._history:
self._parse_headers_raw()
return self._history
示例13: set_cookie
# 需要导入模块: from http.cookiejar import CookieJar [as 别名]
# 或者: from http.cookiejar.CookieJar import set_cookie [as 别名]
def set_cookie(self, cookie):
if self.delayload:
self._delayload_domain(cookie.domain)
CookieJar.set_cookie(self, cookie)
示例14: load_cookie_data
# 需要导入模块: from http.cookiejar import CookieJar [as 别名]
# 或者: from http.cookiejar.CookieJar import set_cookie [as 别名]
def load_cookie_data(self, filename,
ignore_discard=False, ignore_expires=False):
"""Load cookies from file containing actual cookie data.
Old cookies are kept unless overwritten by newly loaded ones.
You should not call this method if the delayload attribute is set.
I think each of these files contain all cookies for one user, domain,
and path.
filename: file containing cookies -- usually found in a file like
C:\WINNT\Profiles\joe\Cookies\[email protected][1].txt
"""
now = int(time.time())
cookie_data = self._load_cookies_from_file(filename)
for cookie in cookie_data:
flags = cookie["FLAGS"]
secure = ((flags & 0x2000) != 0)
filetime = (cookie["HIXP"] << 32) + cookie["LOXP"]
expires = epoch_time_offset_from_win32_filetime(filetime)
if expires < now:
discard = True
else:
discard = False
domain = cookie["DOMAIN"]
initial_dot = domain.startswith(".")
if initial_dot:
domain_specified = True
else:
# MSIE 5 does not record whether the domain cookie-attribute
# was specified.
# Assuming it wasn't is conservative, because with strict
# domain matching this will match less frequently; with regular
# Netscape tail-matching, this will match at exactly the same
# times that domain_specified = True would. It also means we
# don't have to prepend a dot to achieve consistency with our
# own & Mozilla's domain-munging scheme.
domain_specified = False
# assume path_specified is false
# XXX is there other stuff in here? -- e.g. comment, commentURL?
c = Cookie(0,
cookie["KEY"], cookie["VALUE"],
None, False,
domain, domain_specified, initial_dot,
cookie["PATH"], False,
secure,
expires,
discard,
None,
None,
{"flags": flags})
if not ignore_discard and c.discard:
continue
if not ignore_expires and c.is_expired(now):
continue
CookieJar.set_cookie(self, c)