本文整理汇总了Python中Cookie.BaseCookie类的典型用法代码示例。如果您正苦于以下问题:Python BaseCookie类的具体用法?Python BaseCookie怎么用?Python BaseCookie使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了BaseCookie类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: unset_cookie
def unset_cookie(self, key, strict=True):
"""
Unset a cookie with the given name (remove it from the
response). If there are multiple cookies (e.g., two cookies
with the same name and different paths or domains), all such
cookies will be deleted.
"""
existing = self.headers.getall('Set-Cookie')
if not existing:
if not strict:
return
raise KeyError("No cookies at all have been set")
del self.headers['Set-Cookie']
found = False
for header in existing:
cookies = BaseCookie()
cookies.load(header)
if key in cookies:
found = True
del cookies[key]
self._add_cookie(cookies)
else:
# this branching is required because Cookie.Morsel.output()
# strips quotes from expires= parameter, so better use
# it as is, if it hasn't changed
self._add_cookie(header)
if strict and not found:
raise KeyError(
"No cookie has been set with the name %r" % key)
示例2: unset_cookie
def unset_cookie(self, key):
"""
Unset a cookie with the given name (remove it from the
response). If there are multiple cookies (e.g., two cookies
with the same name and different paths or domains), all such
cookies will be deleted.
"""
existing = self.response.headers.get_all('Set-Cookie')
if not existing:
raise KeyError(
"No cookies at all have been set")
del self.response.headers['Set-Cookie']
found = False
for header in existing:
cookies = BaseCookie()
cookies.load(header)
if key in cookies:
found = True
del cookies[key]
header = cookies.output(header='').lstrip()
if header:
self.response.headers.add('Set-Cookie', header)
if not found:
raise KeyError(
"No cookie has been set with the name %r" % key)
示例3: do_request
def do_request(self, req, status, expect_errors):
"""
Override webtest.TestApp's method so that we do real HTTP requests
instead of WSGI calls.
"""
headers = {}
if self.cookies:
c = BaseCookie()
for name, value in self.cookies.items():
c[name] = value
hc = '; '.join(['='.join([m.key, m.value]) for m in c.values()])
req.headers['Cookie'] = hc
res = self._do_httplib_request(req)
# Set these attributes for consistency with webtest.
res.request = req
res.test_app = self
if not expect_errors:
self._check_status(res.status_int, res)
self._check_errors(res)
res.cookies_set = {}
# merge cookies back in
self.cookiejar.extract_cookies(ResponseCookieAdapter(res),
RequestCookieAdapter(req))
return res
示例4: unset_cookie
def unset_cookie(self, key):
""" Unset a cookie with the given name (remove from the response).
If there are multiple cookies (e.g., two cookies with the same name and
different paths or domains), all such cookies will be deleted.
Args:
key: string that is the cookie's name (mandatory)
Side effects:
delete from self.response.headers all cookies with that name
Raises:
KeyError if the response had no such cookies (or, none at all)
"""
existing = self.response.headers.getall('Set-Cookie')
if not existing: raise KeyError("No cookies at all had been set")
# remove all set-cookie headers, then put back those (if any) that
# should not be removed
del self.response.headers['Set-Cookie']
found = False
for header in existing:
cookies = BaseCookie()
cookies.load(header)
if key in cookies:
found = True
del cookies[key]
header = cookies.output(header='').lstrip()
if header:
self.response.headers.add_header('Set-Cookie', header)
if not found: raise KeyError("No cookie had been set with name %r" % key)
示例5: do_request
def do_request(self, req, status, expect_errors):
"""
Override webtest.TestApp's method so that we do real HTTP requests
instead of WSGI calls.
"""
headers = {}
if self.cookies:
c = BaseCookie()
for name, value in self.cookies.items():
c[name] = value
hc = '; '.join(['='.join([m.key, m.value]) for m in c.values()])
req.headers['Cookie'] = hc
res = self._do_httplib_request(req)
# Set these attributes for consistency with webtest.
res.request = req
res.test_app = self
if not expect_errors:
self._check_status(res.status_int, res)
self._check_errors(res)
res.cookies_set = {}
for header in res.headers.getall('set-cookie'):
try:
c = BaseCookie(header)
except CookieError, e:
raise CookieError(
"Could not parse cookie header %r: %s" % (header, e))
for key, morsel in c.items():
self.cookies[key] = morsel.value
res.cookies_set[key] = morsel.value
示例6: load
def load(self, rawdata):
self.bad_cookies = []
self._BaseCookie__set = self._loose_set
BaseCookie.load(self, rawdata)
self._BaseCookie__set = self._strict_set
for key in self.bad_cookies:
del self[key]
示例7: do_request
def do_request(self, req):
errors = StringIO()
req.environ['wsgi.errors'] = errors
if self.cookies:
cookie_header = ''.join([
'%s="%s"; ' % (name, cookie_quote(value))
for name, value in self.cookies.items()])
req.environ['HTTP_COOKIE'] = cookie_header
res = req.get_response(self.application, catch_exc_info=True)
# We do this to make sure the app_iter is exausted:
res.body
res.errors = errors.getvalue()
res.cookies_set = {}
for header in res.headers.getall('set-cookie'):
try:
c = BaseCookie(header)
except CookieError, e:
raise CookieError(
"Could not parse cookie header %r: %s" % (header, e))
for key, morsel in c.items():
self.cookies[key] = morsel.value
res.cookies_set[key] = morsel.value
示例8: prepareResponse
def prepareResponse(self, response):
for key, value in response.headers.items():
if key.lower() == "set-cookie":
cookie = BaseCookie(value)
# use all attributes but 'secure', because then the browser won't send the cookie anymore
value = cookie.output(attrs=['expires','path','comment','domain','max-age','secure','version','httponly'], header="")
self.setHeader(key, value)
self.setResponseCode(response.code)
示例9: parse_cookies
def parse_cookies(response):
"""
Return a ``Cookie.BaseCookie`` object populated from cookies parsed from
the response object
"""
base_cookie = BaseCookie()
for item in response.headers.get_all('Set-Cookie'):
base_cookie.load(item)
return base_cookie
示例10: do_request
def do_request(self, req, status, expect_errors):
"""
Executes the given request (``req``), with the expected
``status``. Generally ``.get()`` and ``.post()`` are used
instead.
"""
__tracebackhide__ = True
errors = StringIO()
req.environ["wsgi.errors"] = errors
if self.cookies:
c = BaseCookie()
for name, value in self.cookies.items():
c[name] = value
req.environ["HTTP_COOKIE"] = str(c).split(": ", 1)[1]
req.environ["paste.testing"] = True
req.environ["paste.testing_variables"] = {}
app = lint.middleware(self.app)
old_stdout = sys.stdout
out = CaptureStdout(old_stdout)
try:
sys.stdout = out
start_time = time.time()
## FIXME: should it be an option to not catch exc_info?
res = req.get_response(app, catch_exc_info=True)
end_time = time.time()
finally:
sys.stdout = old_stdout
sys.stderr.write(out.getvalue())
res.app = app
res.test_app = self
# We do this to make sure the app_iter is exausted:
res.body
res.errors = errors.getvalue()
total_time = end_time - start_time
for name, value in req.environ["paste.testing_variables"].items():
if hasattr(res, name):
raise ValueError(
"paste.testing_variables contains the variable %r, but "
"the response object already has an attribute by that "
"name" % name
)
setattr(res, name, value)
if not expect_errors:
self._check_status(status, res)
self._check_errors(res)
res.cookies_set = {}
for header in res.headers.getall("set-cookie"):
try:
c = BaseCookie(header)
except CookieError, e:
raise CookieError("Could not parse cookie header %r: %s" % (header, e))
for key, morsel in c.items():
self.cookies[key] = morsel.value
res.cookies_set[key] = morsel.value
示例11: _parse_cookies
def _parse_cookies(self, environ) :
_QUOTES_RE = re.compile('"(.*)"')
source=environ.get('HTTP_COOKIE', '')
vars = {}
if source:
cookies = BaseCookie()
cookies.load(source)
for name in cookies:
value = cookies[name].value
unquote_match = _QUOTES_RE.match(value)
if unquote_match is not None:
value = unquote_match.group(1)
vars[name] = value
return vars
示例12: _get_cookies
def _get_cookies(environ):
"""
Return a *plain* dictionary of cookies as found in the request.
"""
source = environ.get('HTTP_COOKIE', '')
if 'webob._parsed_cookies' in environ:
vars_, var_source = environ['webob._parsed_cookies']
if var_source == source:
return vars_
vars_ = {}
if source:
cookies = BaseCookie()
cookies.load(source)
for name in cookies:
vars_[name] = cookies[name].value
environ['webob._parsed_cookies'] = (vars_, source)
return vars_
示例13: transferCookiesToSafari
def transferCookiesToSafari():
"""
Copy all crunchyroll cookies from Plex's cookie storage
into Safari's Plist
"""
import platform
if "darwin" in platform.system().lower():
cookieString = HTTP.GetCookiesForURL(BASE_URL)
if not cookieString: return True
try:
theCookies = BaseCookie(cookieString)
appendThis = []
tomorrow = datetime.now() + timedelta((1))
for k, v in theCookies.items():
#Plex doesn't supply these, so:
cookieDict = {'Domain':".crunchyroll.com",
'Path':"/",
'Expires': tomorrow,
'Created': time.time(),
'Name': k,
'Value': v.value
}
appendThis.append(cookieDict)
#Log.Debug("#######Transferring these cookies:")
#Log.Debug(appendThis)
filename = os.path.expanduser("~/Library/Cookies/Cookies.plist")
theList = plistlib.readPlist(filename)
finalCookies = appendThis
# brute force replace
for item in theList:
if not "crunchyroll.com" in item['Domain']:
finalCookies.append(item)
plistlib.writePlist(finalCookies, filename)
return True
except Exception, arg:
Log.Error("#########transferCookiesToSafari() Exception occured:")
Log.Error(repr(Exception) + " " + repr(arg))
return False
示例14: set_cookie
def set_cookie(self, name, value, domain=None, expires=None, path='/',
expires_days=None):
"""Sets the given cookie name/value with the given options.
:param name:
Cookie name.
:param value:
Cookie value.
:param domain:
Cookie domain.
:param expires:
A expiration date as a `datetime` object.
:param path:
Cookie path.
:param expires_days:
Number of days to calculate expiration.
:return:
`None`.
"""
if expires_days is not None and not expires:
expires = datetime.datetime.utcnow() + datetime.timedelta(
days=expires_days)
cookie = BaseCookie()
cookie[name] = str(base64.b64encode(value))
if expires:
timestamp = calendar.timegm(expires.utctimetuple())
expires = email.utils.formatdate(timestamp, localtime=False,
usegmt=True)
cookie[name]['expires'] = expires
if path:
cookie[name]['path'] = path
if domain:
cookie[name]['domain'] = domain
cookie_str = cookie.output()
if cookie_str.startswith('Set-Cookie:'):
cookie_str = cookie_str[11:].strip()
self._response.headers.add_header('Set-Cookie', cookie_str)
示例15: unset_cookie
def unset_cookie(self, key):
existing = self.headers.get_all('Set-Cookie')
if not existing:
raise KeyError('No cookies have been set')
del self.headers['Set-Cookie']
found = False
for header in existing:
cookies = BaseCookie()
cookies.load(header)
if key in cookies:
found = True
del cookies[key]
header = cookies.output(header='').lstrip()
if header:
if header.endswith(';'):
header = header[:-1]
self.headers.add_header('Set-Cookie', header)
if not found:
raise KeyError('No cookie has been set with the name %r' % key)