本文整理汇总了Python中Cookie.BaseCookie.items方法的典型用法代码示例。如果您正苦于以下问题:Python BaseCookie.items方法的具体用法?Python BaseCookie.items怎么用?Python BaseCookie.items使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Cookie.BaseCookie
的用法示例。
在下文中一共展示了BaseCookie.items方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: do_request
# 需要导入模块: from Cookie import BaseCookie [as 别名]
# 或者: from Cookie.BaseCookie import items [as 别名]
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
示例2: do_request
# 需要导入模块: from Cookie import BaseCookie [as 别名]
# 或者: from Cookie.BaseCookie import items [as 别名]
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
示例3: do_request
# 需要导入模块: from Cookie import BaseCookie [as 别名]
# 或者: from Cookie.BaseCookie import items [as 别名]
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
示例4: transferCookiesToSafari
# 需要导入模块: from Cookie import BaseCookie [as 别名]
# 或者: from Cookie.BaseCookie import items [as 别名]
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
示例5: do_request
# 需要导入模块: from Cookie import BaseCookie [as 别名]
# 或者: from Cookie.BaseCookie import items [as 别名]
def do_request(self, req, status, expect_errors):
"""
Executes the given request (``req``), with the expected
``status``. Generally ``.get()`` and ``.post()`` are used
instead.
To use this::
resp = app.do_request(webtest.TestRequest.blank(
'url', ...args...))
Note you can pass any keyword arguments to
``TestRequest.blank()``, which will be set on the request.
These can be arguments like ``content_type``, ``accept``, etc.
"""
__tracebackhide__ = True
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
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
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
示例6: TestAgent
# 需要导入模块: from Cookie import BaseCookie [as 别名]
# 或者: from Cookie.BaseCookie import items [as 别名]
class TestAgent(object):
"""
A ``TestAgent`` object provides a user agent for the WSGI application under
test.
Key methods and properties:
- ``get(path)``, ``post(path)``, ``post_multipart`` - create get/post
requests for the WSGI application and return a new ``TestAgent`` object
- ``request``, ``response`` - the `werkzeug` request and
response objects associated with the last WSGI request.
- ``body`` - the body response as a string
- ``lxml`` - the lxml representation of the response body (only
applicable for HTML responses)
- ``reset()`` - reset the TestAgent object to its initial
state, discarding any form field values
- ``find()`` (or dictionary-style attribute access) - evalute the given
xpath expression against the current response body and return a list.
"""
response_class = wz.Response
_lxml= None
environ_defaults = {
'SCRIPT_NAME': "",
'PATH_INFO': "",
'QUERY_STRING': "",
'SERVER_NAME': "localhost",
'SERVER_PORT': "80",
'SERVER_PROTOCOL': "HTTP/1.0",
'REMOTE_ADDR': '127.0.0.1',
'wsgi.version': (1, 0),
'wsgi.url_scheme': 'http',
'wsgi.multithread': False,
'wsgi.multiprocess': False,
'wsgi.run_once': False,
}
def __init__(self, app, request=None, response=None, cookies=None, history=None, validate_wsgi=False):
# TODO: Make validate_wsgi pass
if validate_wsgi:
app = wsgi_validator(app)
self.app = app
self.request = request
self.response = response
self._elements = []
# Stores file upload field values in forms
self.file_uploads = {}
if cookies:
self.cookies = cookies
else:
self.cookies = BaseCookie()
if response:
self.cookies.update(parse_cookies(response))
if history:
self.history = history
else:
self.history = []
@classmethod
def make_environ(cls, REQUEST_METHOD='GET', PATH_INFO='', wsgi_input='', **kwargs):
SCRIPT_NAME = kwargs.pop('SCRIPT_NAME', cls.environ_defaults["SCRIPT_NAME"])
if SCRIPT_NAME and SCRIPT_NAME[-1] == "/":
SCRIPT_NAME = SCRIPT_NAME[:-1]
PATH_INFO = "/" + PATH_INFO
if not SCRIPT_NAME:
assert not PATH_INFO.startswith('.')
environ = cls.environ_defaults.copy()
environ.update(kwargs)
for key, value in kwargs.items():
environ[key.replace('wsgi_', 'wsgi.')] = value
if isinstance(wsgi_input, basestring):
wsgi_input = StringIO(wsgi_input)
environ.update({
'REQUEST_METHOD': REQUEST_METHOD,
'SCRIPT_NAME': SCRIPT_NAME,
'PATH_INFO': PATH_INFO,
'wsgi.input': wsgi_input,
'wsgi.errors': StringIO(),
})
if environ['SCRIPT_NAME'] == '/':
environ['SCRIPT_NAME'] = ''
environ['PATH_INFO'] = '/' + environ['PATH_INFO']
while PATH_INFO.startswith('//'):
PATH_INFO = PATH_INFO[1:]
#.........这里部分代码省略.........