我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用Cookie.SimpleCookie()。
def _parse_cookies(cookie_str, dictionary): """Tries to parse any key-value pairs of cookies in a string, then updates the the dictionary with any key-value pairs found. **Example**:: dictionary = {} _parse_cookies('my=value', dictionary) # Now the following is True dictionary['my'] == 'value' :param cookie_str: A string containing "key=value" pairs from an HTTP "Set-Cookie" header. :type cookie_str: ``str`` :param dictionary: A dictionary to update with any found key-value pairs. :type dictionary: ``dict`` """ parsed_cookie = Cookie.SimpleCookie(cookie_str) for cookie in parsed_cookie.values(): dictionary[cookie.key] = cookie.coded_value
def __init__(self, env): Storage.__init__(self) self.env = Storage(env) self.env.web2py_path = global_settings.applications_parent self.env.update(global_settings) self.cookies = Cookie.SimpleCookie() self._get_vars = None self._post_vars = None self._vars = None self._body = None self.folder = None self.application = None self.function = None self.args = List() self.extension = 'html' self.now = datetime.datetime.now() self.utcnow = datetime.datetime.utcnow() self.is_restful = False self.is_https = False self.is_local = False self.global_settings = settings.global_settings self._uuid = None
def __init__(self): Storage.__init__(self) self.status = 200 self.headers = dict() self.headers['X-Powered-By'] = 'web2py' self.body = cStringIO.StringIO() self.session_id = None self.cookies = Cookie.SimpleCookie() self.postprocessing = [] self.flash = '' # used by the default view layout self.meta = Storage() # used by web2py_ajax.html self.menu = [] # used by the default view layout self.files = [] # used by web2py_ajax.html self._vars = None self._caller = lambda f: f() self._view_environment = None self._custom_commit = None self._custom_rollback = None self.generic_patterns = ['*'] self.delimiters = ('{{', '}}') self.formstyle = 'table3cols' self.form_label_separator = ': '
def getSession(self, clear_cookie=False): sid = None if ('Cookie' in self.request_handler.headers): cookie = Cookie.SimpleCookie() cookie.load(self.request_handler.headers.getheader('Cookie')) if ('sid' in cookie and cookie['sid']): sid = cookie['sid'].value if not sid or clear_cookie: cookie = Cookie.SimpleCookie() sid = str(sha.new(repr(time.time())).hexdigest()) cookie['sid'] = sid cookie['sid']['path'] = '/' expires = (time.time() + 14 * 24 * 3600) cookie['sid']['expires'] = time.strftime("%a, %d-%b-%Y %T GMT", time.gmtime(expires)) cookie_output = cookie.output().split(': ') RedisConnection.hset('session_' + str(sid), 'exists', '1') self.headers[cookie_output[0]] = cookie_output[1] return sid
def createTestSession(username=None, password=None, admin=True): """Creates a test session and, if provided, sets up authentication""" # Create session sid sid = 'test_session' # Create user object, if it doesn't already exist try: User.objects.get(uid=username) except Exception: User(uid=username, admin=admin).save() # Create cookie for setting header cookie = Cookie.SimpleCookie() cookie['sid'] = sid cookie['sid']['expires'] = 24 * 60 * 60 RedisConnection.hset('session_' + sid, 'username', username) RedisConnection.hset('session_' + sid, 'password', password) return sid, cookie.output()
def __init__(self, conpool=None, cookie_str=None, throw_exception=True): """conpool: ?????????????? int???? 10 cookie_str: ??????? Cookie???? String throw_exception: ????????????? bool???? True """ self.throw_exception = throw_exception if conpool is None: self.conpool = httpconpool(10) else: self.conpool = conpool self.initcookie = Cookie.SimpleCookie() if cookie_str: if not cookie_str.endswith(';'): cookie_str += ";" for cookiepart in cookie_str.split(";"): if cookiepart.strip() != "": cookiekey, cookievalue = cookiepart.split("=", 1) self.initcookie[cookiekey.strip()] = cookievalue.strip() self.cookiepool = {}
def get_user_info(http_cookie, cookie_name=_COOKIE_NAME): """Gets the requestor's user info from an HTTP Cookie header. Args: http_cookie: The value of the 'Cookie' HTTP request header. cookie_name: The name of the cookie that stores the user info. Returns: A tuple (email, admin, user_id) where: email: The user's email address, if any. admin: True if the user is an admin; False otherwise. user_id: The user ID, if any. """ try: cookie = Cookie.SimpleCookie(http_cookie) except Cookie.CookieError: return '', False, '' cookie_dict = dict((k, v.value) for k, v in cookie.iteritems()) return _get_user_info_from_dict(cookie_dict, cookie_name)
def _set_user_info_cookie(email, admin, cookie_name=_COOKIE_NAME): """Creates a cookie to set the user information for the requestor. Args: email: The email to set for the user. admin: True if the user should be admin; False otherwise. cookie_name: The name of the cookie that stores the user info. Returns: Set-Cookie value for setting the user info of the requestor. """ cookie_value = _create_cookie_data(email, admin) cookie = Cookie.SimpleCookie() cookie[cookie_name] = cookie_value cookie[cookie_name]['path'] = '/' return cookie[cookie_name].OutputString()
def cookies(*requireds, **defaults): """ Returns a `storage` object with all the cookies in it. See `storify` for how `requireds` and `defaults` work. """ cookie = Cookie.SimpleCookie() cookie.load(ctx.env.get('HTTP_COOKIE', '')) try: return storify(cookie, *requireds, **defaults) except KeyError: badrequest() raise StopIteration ########################################################## ## WSGI Sugar ##########################################################
def _verify(self, environ, start_response): logger = self.config['logger'] ctx = px_context.build_context(environ, self.config) if ctx.get('module_mode') == 'inactive' or is_static_file(ctx): logger.debug('Filter static file request. uri: ' + ctx.get('uri')) return self.app(environ, start_response) cookies = Cookie.SimpleCookie(environ.get('HTTP_COOKIE')) if self.config.get('captcha_enabled') and cookies.get('_pxCaptcha') and cookies.get('_pxCaptcha').value: pxCaptcha = cookies.get('_pxCaptcha').value if px_captcha.verify(ctx, self.config, pxCaptcha): logger.debug('User passed captcha verification. user ip: ' + ctx.get('socket_ip')) return self.app(environ, start_response) # PX Cookie verification if not px_cookie.verify(ctx, self.config) and self.config.get('server_calls_enabled', True): # Server-to-Server verification fallback if not px_api.verify(ctx, self.config): return self.app(environ, start_response) return self.handle_verification(ctx, self.config, environ, start_response)
def _get_cookie_dict(req): if 'Cookie' in req.headers_in: cookie = Cookie.SimpleCookie() cookie.load(str(req.headers_in['Cookie'])) return dict((key, c.value) for key, c in cookie.items()) else: return {} # # module initializations # # we try to filter out stupid warnings from third party libraries that end up # in the apache logs. it won't help on first invocation though, # since the errors are in mod_python itself, and mod_python is used to load # this module. #
def cookies(self): """ Cookies parsed into a :class:`FormsDict`. Signed cookies are NOT decoded. Use :meth:`get_cookie` if you expect signed cookies. """ cookies = SimpleCookie(self.environ.get('HTTP_COOKIE', '')).values() return FormsDict((c.key, c.value) for c in cookies)
def copy(self, cls=None): """ Returns a copy of self. """ cls = cls or BaseResponse assert issubclass(cls, BaseResponse) copy = cls() copy.status = self.status copy._headers = dict((k, v[:]) for (k, v) in self._headers.items()) if self._cookies: copy._cookies = SimpleCookie() copy._cookies.load(self._cookies.output(header='')) return copy
def setCookie(self, key=None ,value=None): if key : c1 = Cookie.SimpleCookie() c1[key] = value cinfo = self.getDefaultCinfo() for attr,val in cinfo.items(): c1[key][attr] = val if c1 not in self.cookies: self.cookies.append(c1)
def __init__(self): self.sid = None self.key = None self.session = None string_cookie = os.environ.get('HTTP_COOKIE', '') self.cookie = Cookie.SimpleCookie() self.cookie.load(string_cookie) # check for existing cookie if self.cookie.get(COOKIE_NAME): self.sid = self.cookie[COOKIE_NAME].value self.key = "session-" + self.sid self.session = memcache.get(self.key) if self.session is None: logging.info("Invalidating session "+self.sid) self.sid = None self.key = None if self.session is None: self.sid = str(random.random())[5:]+str(random.random())[5:] self.key = "session-" + self.sid logging.info("Creating session "+self.key); self.session = dict() memcache.add(self.key, self.session, 3600) self.cookie[COOKIE_NAME] = self.sid self.cookie[COOKIE_NAME]['path'] = DEFAULT_COOKIE_PATH # Send the Cookie header to the browser print self.cookie # Private method to update the cache on modification
def ResetCookies(self): '''Empty the list of cookies. ''' self.cookies = Cookie.SimpleCookie()
def __init__(self): self.cookies = Cookie.SimpleCookie();
def cookies(self): """ Cookies parsed into a :class:`FormsDict`. Signed cookies are NOT decoded. Use :meth:`get_cookie` if you expect signed cookies. """ cookies = SimpleCookie(self.environ.get('HTTP_COOKIE','')).values() return FormsDict((c.key, c.value) for c in cookies)
def copy(self, cls=None): ''' Returns a copy of self. ''' cls = cls or BaseResponse assert issubclass(cls, BaseResponse) copy = cls() copy.status = self.status copy._headers = dict((k, v[:]) for (k, v) in self._headers.items()) if self._cookies: copy._cookies = SimpleCookie() copy._cookies.load(self._cookies.output(header='')) return copy
def copy(self, cls=None): """ Returns a copy of self. """ cls = cls or BaseResponse assert issubclass(cls, BaseResponse) copy = cls() copy.status = self.status copy._headers = dict((k, v[:]) for (k, v) in self._headers.items()) if self._cookies: copy._cookies = SimpleCookie() copy._cookies.load(self._cookies.output()) return copy
def copy(self, cls=None): ''' Returns a copy of self. ''' cls = cls or BaseResponse assert issubclass(cls, BaseResponse) copy = cls() copy.status = self.status copy._headers = dict((k, v[:]) for (k, v) in self._headers.items()) if self._cookies: copy._cookies = SimpleCookie() copy._cookies.load(self._cookies.output()) return copy
def cookies(self): """ Cookies parsed into a :class:`FormsDict`. Signed cookies are NOT decoded. Use :meth:`get_cookie` if you expect signed cookies. """ cookies = SimpleCookie(self.environ.get('HTTP_COOKIE','')) cookies = list(cookies.values())[:self.MAX_PARAMS] return FormsDict((c.key, c.value) for c in cookies)
def COOKIES(self): """ A dict-like SimpleCookie instance. This should not be used directly. See :meth:`set_cookie`. """ depr('The COOKIES dict is deprecated. Use `set_cookie()` instead.') # 0.10 if not self._cookies: self._cookies = SimpleCookie() return self._cookies