当前位置: 首页>>代码示例>>Python>>正文


Python SimpleCookie.values方法代码示例

本文整理汇总了Python中Cookie.SimpleCookie.values方法的典型用法代码示例。如果您正苦于以下问题:Python SimpleCookie.values方法的具体用法?Python SimpleCookie.values怎么用?Python SimpleCookie.values使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Cookie.SimpleCookie的用法示例。


在下文中一共展示了SimpleCookie.values方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _parse_cookie

# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import values [as 别名]
 def _parse_cookie(self):
     cookiestr = self.environ.get('HTTP_COOKIE', '')
     if not cookiestr:
         return
     cookies = SimpleCookie(cookiestr)
     for c in cookies.values():
         self.cookie[c.key] = c.value
开发者ID:zhaoweikid,项目名称:zbase,代码行数:9,代码来源:http.py

示例2: CookieHandler

# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import values [as 别名]
class CookieHandler(object):

    def __init__(self, *args, **kw):
        # Somewhere to store cookies between consecutive requests
        self.cookies = SimpleCookie()
        super(CookieHandler, self).__init__(*args, **kw)

    def httpCookie(self, path):
        """Return self.cookies as an HTTP_COOKIE environment value."""
        l = [m.OutputString().split(';')[0] for m in self.cookies.values()
             if path.startswith(m['path'])]
        return '; '.join(l)

    def loadCookies(self, envstring):
        self.cookies.load(envstring)

    def saveCookies(self, response):
        """Save cookies from the response."""
        # Urgh - need to play with the response's privates to extract
        # cookies that have been set
        # TODO: extend the IHTTPRequest interface to allow access to all
        # cookies
        # TODO: handle cookie expirations
        for k, v in response._cookies.items():
            k = k.encode('utf8')
            self.cookies[k] = v['value'].encode('utf8')
            if 'path' in v:
                self.cookies[k]['path'] = v['path']
开发者ID:jean,项目名称:zope.app.testing,代码行数:30,代码来源:functional.py

示例3: Response

# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import values [as 别名]
class Response(object):
    def __init__(self, content='', status=200, mimetype='text/html', charset='utf-8'):
        self.content = content
        self.status  = status
        self.mimetype= mimetype
        self.headers = {'X-Powered-By':'QF/'+version}
        self.cookies = SimpleCookie()
        self.charset = charset

        self.headers['Content-Type'] = '%s; charset=%s' % (self.mimetype, self.charset)

    # TODO secure 没有实现
    def set_cookie(self, key, value='', secure=None, **options):
        '''
        option : max_age, expires, path, domain, httponly
        '''
        self.cookies[key] = value
        self.cookies[key]['path'] = '/'

        for k, v in options.items():
            if v:
                if k == 'expires':
                    if isinstance(v, (datetime.date, datetime.datetime)):
                        v = v.timetuple()
                    elif isinstance(v, (int, float)):
                        v = time.gmtime(v)
                    v = time.strftime("%a, %d %b %Y %H:%M:%S GMT", v)
                self.cookies[key][k.replace('_', '-')] = v

    def del_cookie(self, key, **kwargs):
        kwargs['max_age'] = -1
        kwargs['expires'] = 0
        self.set_cookie(key, '', **kwargs)

    def write(self, data):
        if type(data) == types.UnicodeType:
            self.content += data.encode(self.charset)
        else:
            self.content += data

    def length(self):
        return len(self.content)

    def redirect(self, url):
        url = url.encode(self.charset) if isinstance(url,unicode) else str(url)
        self.status = 302
        self.headers['Location'] = url

    def __call__(self, environ, start_response):
        statusstr = '%d %s' % (self.status, HTTP_STATUS_CODES.get(self.status, ''))
        self.headers['Content-Length'] = str(len(self.content))

        headers = self.headers.items()
        # add cookie
        if self.cookies:
            for c in self.cookies.values():
                headers.append(('Set-Cookie', c.OutputString()))

        start_response(statusstr, headers)
        return [self.content]
开发者ID:zhaoweikid,项目名称:zbase,代码行数:62,代码来源:http.py

示例4: session_response

# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import values [as 别名]
 def session_response(status, headers, exc_info=None):
     sid = data.session.save()
     if sid:
         cookie = SimpleCookie()
         cookie[self.cookie_name] = sid
         cookie[self.cookie_name]['path'] = '/'
         cookie[self.cookie_name]['expires'] = self.ttl
         headers.append(('Set-Cookie', morsel.OutputString())
                        for morsel in cookie.values())
     return start_response(status, headers, exc_info)
开发者ID:improper4,项目名称:py-sessions,代码行数:12,代码来源:session.py

示例5: BaseController

# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import values [as 别名]
class BaseController(WSGIController):

    title = None
    
    def __call__(self, environ, start_response):
        # Insert any code to be run per request here. The Routes match
        # is under environ['pylons.routes_dict'] should you want to check
        # the action or route vars here
        self._cookies = SimpleCookie()
        def repl_start_response(status, headers, exc_info=None):
            for c in self._cookies.values():
                
                headers.append(
                    'Set-Cookie', c.output(header=''))
            return start_response(status, headers, exc_info)
        return WSGIController.__call__(self, environ, repl_start_response)

    def __before__(self):
        request.charset = 'utf8'
        c.self = self
        if self.title is None:
            c.title = self.__class__.__name__[:-len('Controller')]
        else:
            c.title = self.title
        c.url = URL.from_environ(
            request.environ,
            script_name=request.environ['paste.recursive.script_name'],
            with_path_info=False)
        c.session = session
        if 'bundle' in request.urlvars:
            self.bundle = model.Bundle.get(request.urlvars['bundle'])
            c.bundle_url = c.url[self.bundle.name]
        else:
            self.bundle = None
            c.bundle_url = None
        if request.cookies.get('flash'):
            c.flash = request.cookies['flash']
            self.delete_cookie('flash')
        else:
            c.flash = None

    def flash(self, msg):
        self.set_cookie('flash', msg)

    def set_cookie(self, key, value='', **kw):
        kw.setdefault('path', '/')
        self._cookies[key] = value
        for var_name, var_value in kw.items():
            if var_value is not None and var_value is not False:
                self._cookies[key][var_name.replace('_', '-')] = var_value

    def delete_cookie(self, key, path='/', domain=None):
        self.set_cookie(key, '', path=path, domain=domain,
                        expires=0, max_age=0)
开发者ID:iitwebdev,项目名称:lectures,代码行数:56,代码来源:base.py

示例6: set

# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import values [as 别名]
	def set(self, username, expires=None):
		s = username + ":" + self.req._ENV.get('REMOTE_ADDR', '-')
		s_hash = hashlib.sha1(s + config.secret).hexdigest()

		session_cookie = SimpleCookie()
		session_cookie['clamsession'] = s + ":" + s_hash
		session_cookie['clamsession']["path"] = '/'
		session_cookie['clamsession']["httponly"] = True
		if expires:
			session_cookie['clamsession']["expires"] = expires
		self.req.headers += [("set-cookie", m.OutputString()) for m in session_cookie.values()]
		return True
开发者ID:stevommmm,项目名称:clam,代码行数:14,代码来源:default_session.py

示例7: get_the_cookie

# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import values [as 别名]
def get_the_cookie(url, username=None, password=None):
    req = urlopen(url)
    data = req.read()
    hidden_inputs = re.findall('<INPUT.*HIDDEN.*NAME="(.*)".*VALUE="(.*)">', data)
    if username is None:
        username = raw_input('Username: ')
    if password is None:
        password = getpass()

    hidden_inputs.append(('username', username))
    hidden_inputs.append(('passcode', password))
    qs = urlencode(hidden_inputs)

    action = urljoin(url, re.findall('<FORM action="([^"]*)" .*>', data)[0])
    req2 = urlopen(action, data=qs)
    cookie = SimpleCookie(req2.info()['set-cookie'])
    return cookie.keys()[0] + "=" + cookie.values()[0].value
开发者ID:cosmin,项目名称:hgformlogin,代码行数:19,代码来源:formloginrepo.py

示例8: Rs

# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import values [as 别名]
class Rs(threading.local):
    def b(self, s, app):
        self.s=s;self.app=app;self.status=status(200);self.header={}
        self.content_type='text/html; charset=UTF-8'
        self.cookies=SimpleCookie()

    def headers(self):
        a=map(lambda c:('Set-Cookie',c.OutputString()),self.cookies.values())
        return list(self.header.iteritems())+a

    def c(self):return self.header['Content-Type']
    def d(self, v):self.header['Content-Type']=v
    content_type=property(c,d,None,c.__doc__)

    def set_cookie(self, k, v, **kargs):
        self.cookies[k]=cookie_encode(v,self.app.config['SECURECOOKIE_KEY'])
        for i,j in kargs.iteritems():self.cookies[k][i.replace('_','-')]=j
开发者ID:hashmalech,项目名称:orvet,代码行数:19,代码来源:orvet.py

示例9: Response

# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import values [as 别名]
class Response(object):
    """ Response object which `start_response`. """
    def bind(self, code=200, content_type="text/html; charset=UTF-8"):
        self.status = _HTTP_STATUS.get(code, "UNKNOWN")
        self.headers = [("Content-Type", content_type)]
        self._response = []

    def redirect(self, url):
        self.headers.append(("Location", url))

    def write(self, msg):
        self._response.append(msg)

    def set_cookie(self, key, value="", max_age=None, expires=None,
                   path="/", domain=None, secure=None):
        if not hasattr(self, "_cookies"):
            self._cookies = SimpleCookie()
        self._cookies[key] = value
        if max_age:
            self._cookies[key]["max-age"] = max_age
        if expires:
            self._cookies[key]["expires"] = _format_gmt_time(expires)
        if path:
            self._cookies[key]["path"] = path
        if domain:
            self._cookies[key]["domain"] = domain
        if secure:
            self._cookies[key]["secure"] = secure

    def delete_cookie(self, key):
        if self._cookies is None:
            self._cookies = SimpleCookie()
        if not key in self._cookies:
            self._cookies[key] = ""
        self._cookies[key]["max-age"] = 0

    def __call__(self, start_response):
        self.headers.append(("Content-Length",
                             str(sum(len(n) for n in self._response))))
        if hasattr(self, "_cookies"):
            for morsel in self._cookies.values():
                self.headers.append(("Set-Cookie", morsel.output(header="")))
        start_response(self.status, self.headers)
        return self._response
开发者ID:duquanlong,项目名称:cyanbird,代码行数:46,代码来源:cyanbird.py

示例10: Response

# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import values [as 别名]
class Response(object):
    status_code = 200
    
    def __init__(self, content='', status=None, content_type='text/html; charset=utf8'):
        self.content = content
        
        if status:
            self.status_code = status
        
        self.headers = {'Content-Type': content_type}
        self.cookies = SimpleCookie()
    
    def __str__(self):
        return '\n'.join(['%s: %s' % (key, value) for key, value in self.headers.items()]) + '\n\n' + self.content
    
    def set_cookie(self, key, value='', max_age=None, expires=None, path='/', domain=None, secure=False):
        self.cookies[key] = value
        
        if max_age is not None:
            self.cookies[key]['max-age'] = max_age
        
        if expires is not None:
            self.cookies[key]['expires'] = expires
        
        if path is not None:
            self.cookies[key]['path'] = path
        
        if domain is not None:
            self.cookies[key]['domain'] = domain
        
        if secure:
            self.cookies[key]['secure'] = True
    
    def delete_cookie(self, key, path='/', domain=None):
        self.set_cookie(key, max_age=0, path=path, domain=domain, expires='Thu, 01-Jan-1970 00:00:00 GMT')
    
    def headers_items(self):
        headers = self.headers.items()
        
        for cookie in self.cookies.values():
            headers.append(('Set-Cookie', str(cookie.output(header=''))))
        
        return headers
开发者ID:Derecho,项目名称:rivr,代码行数:45,代码来源:http.py

示例11: COOKIES

# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import values [as 别名]
 def COOKIES(self):
     cookies = SimpleCookie(self._environ.get('HTTP_COOKIE',''))
     self._COOKIES = {}
     for cookie in cookies.values():
         self._COOKIES[cookie.key] = cookie.value
     return self._COOKIES
开发者ID:swinf,项目名称:Swinf,代码行数:8,代码来源:__init__.py

示例12: Request

# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import values [as 别名]
class Request(object):
    '''
        Base request object that provides an abstraction layer over a WSGI interface.
        Request handlers inherit from this class.
    '''

    STATUS_CODES = {
        200: 'OK',
        201: 'Created',
        204: 'No Content',
        301: 'Moved Permanently',
        302: 'Found',
        303: 'See Other',
        400: 'Bad Request',
        401: 'Unauthorized',
        403: 'Forbidden',
        404: 'Not Found',
        405: 'Method Not Allowed',
        500: 'Internal Server Error',
        503: 'Service Unavailable',
    }
    METHODS = ('GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS')

    def __init__(self):
        self.environ = None
        self.response_cookies = SimpleCookie()
        self.request_cookies = SimpleCookie()
        self.unpacked_cookies = {}
        self.parsed_cookies = False
        self.post_data = {}
        self.parsed_post = False
        self.querystring = {}

    def _get_response(self, environ, start_response, method, uri, uri_kwargs):
        self.environ = environ
        self.querystring = parse_qs(environ.get('QUERY_STRING', ''))
        if method not in self.METHODS:
            raise MethodNotPermitted
        response_data, status_code, extra_headers = self._run_hander(method, uri_kwargs)
        status_text = self.STATUS_CODES.get(status_code)
        if not status_text:
            raise InternalServerError
        headers = self._get_response_headers(status_code, extra_headers)
        start_response('{} {}'.format(status_code, status_text), headers)
        return [response_data]

    def _run_hander(self, method, uri_kwargs):
        handler = getattr(self, method.lower(), None)
        if not handler:
            raise MethodNotPermitted
        raw_response = handler(self.environ, **uri_kwargs)
        response_data, status_code, extra_headers = b'', 200, {}
        if type(raw_response) == tuple:
            if len(raw_response) == 3:
                response_data, status_code, extra_headers = raw_response
            elif len(raw_response) == 2:
                response_data, status_code = raw_response
            else:
                raise InternalServerError
        else:
            response_data = raw_response
        return response_data, status_code, extra_headers

    def _get_response_headers(self, status_code, extra_headers):
        headers = []
        has_content_type = False
        has_server = False
        if type(extra_headers) == dict:
            extra_headers = extra_headers.iteritems()
        for (k, v) in extra_headers:
            k = k.lower().replace('_', '-')
            headers.append((k, v))
            if k == 'content-type':
                has_content_type = True
            elif k == 'server':
                has_server = True
        if not has_content_type:
            headers.append(('content-type', 'text/html'))
        if not has_server:
            headers.append(('server', 'crumb mirco wsgi framework'))
        headers.extend(('set-cookie', c.OutputString()) for c in self.response_cookies.values())
        return headers

    def set_cookie(self, name='', value=None, expires=0, path='/'):
        self.response_cookies[name] = value
        self.response_cookies[name]['path'] = path
        if expires > 0:
            self.response_cookies[name]['expires'] = expires

    def get_cookie(self, name=''):
        if not self.parsed_cookies:
            self.unpack_cookies()
        return getattr(self.request_cookies.get(name), 'value', None)

    def unpack_cookies(self):
        raw_cookies = self.environ.get('HTTP_COOKIE')
        if raw_cookies:
            try:
                self.request_cookies.load(raw_cookies)
            except CookieError:
#.........这里部分代码省略.........
开发者ID:meeb,项目名称:crumb,代码行数:103,代码来源:crumb.py

示例13: HttpResponse

# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import values [as 别名]

#.........这里部分代码省略.........
    def __getitem__(self, name):
        self.headers.get(name)

    def __delitem__(self, name):
        del self.headers[name]

    def __contains__(self, name):
        return name in self.headers

    def __len__(self):
        if isinstance(self.response, list):
            length = 0
            for item in self.response:
                length += len(item)
            return length
        try:
            return len(self.response)
        except:
            return 0

    def write(self, d):
        if not isinstance(self.response, list):
            raise TypeError('read only or dynamic response object')
        elif isinstance(d, basestring):
            self.response.append(d)
        else:
            raise TypeError('str or unicode required')

    def set_cookie(self, key, value='', max_age=None, expires=None,
                   path='/', domain=None, secure=None):
        if self._cookies is None:
            self._cookies = SimpleCookie()
        self._cookies[key] = value
        if not max_age is None:
            self._cookies[key]['max-age'] = max_age
        if not expires is None:
            if isinstance(expires, basestring):
                self._cookies[key]['expires'] = expires
                expires = None
            elif isinstance(expires, datetime):
                expires = expires.utctimetuple()
            elif not isinstance(expires, (int, long)):
                expires = gmtime(expires)
            else:
                raise ValueError('datetime or integer required')
            if not expires is None:
                now = gmtime()
                month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
                         'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][now.tm_mon - 1]
                day = ['Monday', 'Tuesday', 'Wednesday', 'Thursday',
                       'Friday', 'Saturday', 'Sunday'][expires.tm_wday]
                date = '%02d-%s-%s' % (
                    now.tm_mday, month, str(now.tm_year)[-2:]
                )
                d = '%s, %s %02d:%02d:%02d GMT' % (day, date, now.tm_hour,
                                                   now.tm_min, now.tm_sec)
                self._cookies[key]['expires'] = d
        if not path is None:
            self._cookies[key]['path'] = path
        if not domain is None:
            self._cookies[key]['domain'] = domain
        if not secure is None:
            self._cookies[key]['secure'] = secure

    def delete_cookie(self, key):
        if self._cookies is None:
            self._cookies = SimpleCookie()
        if not key in self._cookies:
            self._cookies[key] = ''
        self._cookies[key]['max-age'] = 0

    def __call__(self, request):
        if not 'Content-Type' in self.headers:
            self.headers['Content-Type'] = 'text/html; charset=%s' % \
                                           str(request.charset)
        headers = self.headers.get()
        if not self._cookies is None:
            for morsel in self._cookies.values():
                headers.append(('Set-Cookie', morsel.output(header='')))
        status = '%d %s' % (self.status,
                            HTTP_STATUS_CODES.get(self.status, 'UNKNOWN'))
        request.start_response(status, headers)
        if self.response is None:
            yield ''
        elif isinstance(self.response, unicode):
            yield self.response.encode(request.charset)
        elif isinstance(self.response, str):
            yield self.response
        else:
            try:
                iterator = iter(self.response)
            except TypeError:
                raise TypeError('%r is not an valid response' % self.response)
            for line in iterator:
                if isinstance(line, unicode):
                    yield line.encode(request.charset)
                elif isinstance(line, str):
                    yield line
                else:
                    raise TypeError('%r is not string or unicode' % line)
开发者ID:statico,项目名称:friend-rescue,代码行数:104,代码来源:response.py

示例14: SimpleCookie

# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import values [as 别名]
from Cookie import SimpleCookie

session_cookie = SimpleCookie()
session_cookie['session'] = "somedata"
session_cookie['session']["Path"] = '/'

headers = {}
headers.update(("set-cookie", morsel.OutputString())
                   for morsel
                   in session_cookie.values())


print headers
开发者ID:nbari,项目名称:my-sandbox,代码行数:15,代码来源:set_cookie.py

示例15: Controller

# 需要导入模块: from Cookie import SimpleCookie [as 别名]
# 或者: from Cookie.SimpleCookie import values [as 别名]
class Controller(object):
    """
    Moar's Controller class. Aims to be useful. Extend this for your own
    controllers. Any class that implements the get_response_start()
    method can be used in place of this one.
    """

    def __init__(self, config, request):
        """
        Set up basics and defaults, like status codes and headers.
        """
        self.config = config
        self.request = request
        self.code = 200
        self.headers = []
        self.view = {}
        self.cookie = SimpleCookie()
        self.user = None
        self.parse_cookie()

    def parse_cookie(self):
        """
        Helper for parsing cookie data.
        """
        self.cookie = SimpleCookie()
        if 'HTTP_COOKIE' in self.request:
            self.cookie.load(self.request['HTTP_COOKIE'])

    def get_body_params(self):
        """
        Helper function for parsing body params. Body params are only
        used if the right Content-Type header
        (application/x-www-form-urlencoded) is set.
        """
        if 'CONTENT_TYPE' not in self.request:
            return {}
        if self.request['CONTENT_TYPE'] != 'application/x-www-form-urlencoded':
            return {}
        content_length = int(self.request.get('CONTENT_LENGTH', 0))
        return parse_params(self.request['wsgi.input'].read(content_length))

    def get_params(self):
        """
        Parse all parameters and return them.
        """
        params = parse_params(self.request['QUERY_STRING'])
        params.update(self.get_body_params())
        return params

    def get_response_start(self):
        """
        Build a status code string and headers to send.
        """
        send_headers = list(self.headers)
        for morsel in self.cookie.values():
            send_headers.append(
                ('Set-Cookie', morsel.output(header='').strip()))
        return self.code, send_headers

    def get_template_path(self, method, ext=None):
        """
        Build a path to where the templates for this class/method live.
        Can pass an optional file extension.
        """
        if not ext:
            ext = 'tpl'
        obj_name = self.__class__.__name__.lower().replace('controller', '')
        return '%s/%s.%s' % (obj_name, method, ext)

    def render_raw(self, data, method, ext=None):
        """
        Render a template for the current class and given method. Can
        pass an optional file extension.
        """
        request = Environment(loader=FileSystemLoader('templates'))

        template_path = self.get_template_path(method, ext)
        template = request.get_template(template_path)

        view_vars = dict(data)
        view_vars['user'] = self.user

        return template.render(**view_vars)

    def render(self, method, ext=None):
        """
        Render a template for the current class and given method. Use
        the object's view member variable as a data provider. Can pass
        an optional file extension.
        """
        return self.render_raw(self.view, method, ext)
开发者ID:icheishvili,项目名称:moar,代码行数:93,代码来源:Controller.py


注:本文中的Cookie.SimpleCookie.values方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。