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


Python Response.delete_cookie方法代码示例

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


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

示例1: get_user_info

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import delete_cookie [as 别名]
    def get_user_info(self, request, **params):
        """ Display the appropriate user page or discovery page """
        user_info = {}
        user = str(request.sync_info['user'])
        params = {'user': user,
                  'host': self.app.config['oid.host'],
                  'config': self.app.config,
                  'request': request }

        uid = self.get_session_uid(request)
        if uid is not None:
            # Convert the user name to a standardized token
            user_name = extract_username(user)
            user_id = self.app.auth.backend.get_user_id(user_name)
            if user_id == uid:
                # hey that's me !
                user_info = self.app.storage.get_user_info(user_id) or {}
                params['user_info'] = user_info
                params['sig'] = self.gen_signature(uid, request)
        # Use the older style of discovery (with link refs)
        template = get_template('user')
        ct = 'text/html'
        res = template.render(**params)
        response = Response(str(res), content_type=ct)
        if not user_info:
            response.delete_cookie('beaker.session.id')
        return response
开发者ID:rafrombrc,项目名称:FirefoxID-Server,代码行数:29,代码来源:user.py

示例2: login

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import delete_cookie [as 别名]
 def login(self, req):
     """
     The login form.
     """
     if not self.check_ip(req):
         template = HTMLTemplate.from_filename(os.path.join(os.path.dirname(__file__), 'ip_denied.html'))
         return Response(template.substitute(req=req), status='403 Forbidden')
     if req.method == 'POST':
         username = req.str_POST['username']
         password = req.str_POST['password']
         if not self.check_login(username, password):
             msg = 'Invalid username or password'
         else:
             resp = exc.HTTPFound(location=req.params.get('back') or req.application_url)
             resp.set_cookie('__devauth', self.create_cookie(req, username))
             return resp
     else:
         msg = req.params.get('msg')
     back = req.params.get('back') or req.application_url
     if msg == 'expired':
         msg = 'Your session has expired.  You can log in again, or just <a href="%s">return to your previous page</a>' % (
             html_escape(back))
     template = HTMLTemplate.from_filename(os.path.join(os.path.dirname(__file__), 'login.html'))
     resp = Response(template.substitute(req=req, msg=msg, back=back, middleware=self))
     try:
         if req.cookies.get('__devauth'):
             self.read_cookie(req, req.str_cookies['__devauth'])
     except exc.HTTPException:
         # This means the cookie is invalid
         resp.delete_cookie('__devauth')
     return resp
开发者ID:mhammond,项目名称:openwebapps-directory,代码行数:33,代码来源:__init__.py

示例3: store

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import delete_cookie [as 别名]
 def store(self, req):
     req.userid = self.get_userid(req)
     auth = AuthDomain.from_request(req, self)
     authorized = auth.without_lock
     add_cookie = None
     if authorized:
         add_cookie = auth.add_authorization()
     else:
         authorized, add_cookie = auth.authorize()
     if not authorized:
         if auth.has_users():
             resp = Response(
                 status=403,
                 body=open(os.path.join(here, 'login.html')).read())
         else:
             resp = exc.HTTPForbidden()
     elif 'getlink' in req.params:
         resp = Response(
             content_type='application/json',
             body=json.dumps(dict(url=auth.make_link())))
     else:
         resp = self.store_response(req, auth)
     if add_cookie:
         resp.set_cookie(add_cookie[0], add_cookie[1], max_age=datetime.timedelta(days=10 * 365))
     if not req.userid and req.cookies.get(self.auth_app.cookie_name):
         logger.debug('Invalid cookie: %r' % req.cookies.get(self.auth_app.cookie_name))
         ## Invalid cookie:
         resp.delete_cookie(self.auth_app.cookie_name)
     return resp
开发者ID:ianb,项目名称:webannotate,代码行数:31,代码来源:server.py

示例4: test_delete_cookie_with_path

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import delete_cookie [as 别名]
def test_delete_cookie_with_path():
    res = Response()
    res.headers['Set-Cookie'] = 'a=2; Path=/'
    res.delete_cookie('a', path='/abc')
    eq_(res.headerlist[-1][0], 'Set-Cookie')
    val = [ x.strip() for x in res.headerlist[-1][1].split(';')]
    assert len(val) == 4
    val.sort()
    eq_(val[0], 'Max-Age=0')
    eq_(val[1], 'Path=/abc')
    eq_(val[2], 'a=')
    assert val[3].startswith('expires')
开发者ID:GdZ,项目名称:scriptfile,代码行数:14,代码来源:test_response.py

示例5: sign_out

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import delete_cookie [as 别名]
def sign_out(request):

    user_auth = is_auth_user(request)
    # Не авторизованный пользователь не может попость на эту страницу
    if not user_auth:
        return redirect_to_home(request)

    response = Response()
    response.delete_cookie('session_id')

    page_content = {}
    response.text = templates.get_template('sign_out.html').render(page_content)
    return response
开发者ID:AJleksei,项目名称:LigthIt_TZ,代码行数:15,代码来源:views.py

示例6: action_view_GET

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import delete_cookie [as 别名]
 def action_view_GET(self, req, page):
     if not page.exists:
         return exc.HTTPTemporaryRedirect(location=req.url + "?action=edit")
     if req.cookies.get("message"):
         message = req.cookies["message"]
     else:
         message = None
     text = self.view_template.substitute(page=page, req=req, message=message)
     resp = Response(text)
     if message:
         resp.delete_cookie("message")
     else:
         resp.last_modified = page.mtime
         resp.conditional_response = True
     return resp
开发者ID:Poorvak,项目名称:twitter_clone,代码行数:17,代码来源:example.py

示例7: delete_account

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import delete_cookie [as 别名]
def delete_account(request):
    response = Response()

    user_auth = is_auth_user(request)
    # Удалить аккаут может только залогиненый пользователь
    if not user_auth:
        return redirect_to_home(request)

    # Удаляем пользователя из БД
    Users.delete().where(Users.session_id == user_auth.session_id)

    page_content = {}
    # Очищаем cookie
    response.delete_cookie('session_id')
    response.text = templates.get_template('delete_account.html').render(page_content)
    return response
开发者ID:AJleksei,项目名称:LigthIt_TZ,代码行数:18,代码来源:views.py

示例8: __call__

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import delete_cookie [as 别名]
    def __call__(self, environ, start_response):
        req = Request(environ)

        path = req.path_info_peek()

        if path == "theme.html":
            return self.theme(environ, start_response)

        if path == "login":
            return self.login(environ, start_response)
        if path == "logout":
            if '__ac' in req.cookies:
                res = Response()
                res.status = 304
                res.location = "/"
                res.delete_cookie("__ac")
                return res(environ, start_response)
                
        if path == "projects":
            req.path_info_pop()
            project = req.path_info_pop()
            path = req.path_info_peek()

            if path == "info.xml":
                return Response("""
<info>
<policy>medium_policy</policy>
 <featurelets> 
  <featurelet>blog</featurelet> 
  <featurelet>wikis</featurelet> 
  <featurelet>tasks</featurelet> 
  <featurelet>listen</featurelet> 
 </featurelets> 
</info>""", content_type="application/xml")(environ, start_response)
            if path == "members.xml":
                return Response("""
<members> 
 <member> 
  <id>ejucovy</id> 
  <role>ProjectAdmin</role> 
 </member> 
</members>""", content_type="application/xml")(environ, start_response)

        return Response(req.path_info_peek(), content_type='text/plain')(environ, start_response)
开发者ID:Aglafira,项目名称:libopencore,代码行数:46,代码来源:mock_opencore.py

示例9: HTTPResponse

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import delete_cookie [as 别名]
class HTTPResponse(object):
    """
    Wrap WebOb's Response class.
    """

    body = property(lambda self: self._res.body)
    text = property(lambda self: self._res.text)
    content_type = property(lambda self: self._res.content_type)
    status = property(lambda self: self._res.status)
    charset = property(lambda self: self._res.charset)
    headerlist = property(lambda self: self._res.headerlist)

    def __init__(self, body='', status=200, content_type='text/html',
                 charset='UTF-8', headerlist=None):
        """
        body -- str or bytes that specifies the body. Empty str by default.
        status -- int that specifies the status code. 200 by default.
        content_type -- str that specifies the content_type. 'text/html' by default.
        charset -- str that specifies the charset. 'UTF-8' by default.
        headerlist -- list of tuples that specifies the header values. None by default.
        """
        self._res = Response(body, status, headerlist, content_type=content_type,
                             charset=charset)

    def cache_expires(self, seconds):
        """
        Set the response to expire in the specified seconds.

        seconds -- int that specifies the time for the response to expire in seconds.
        """
        self._res.cache_expires(seconds)

    def set_cookie(self, key, value='', max_age=None, path='/', domain=None, secure=False,
                   httponly=False, comment=None, overwrite=False):
        """
        Set cookie.

        key -- str that specifies the cookie name.
        value -- str that specifies the cookie value. None unsets cookie. Empty str by default.
        max_age -- int that specifies the 'Max-Age' attribute in seconds. None sets a session
                   cookie. None by default.
        path -- str that specifies the 'Path' attribute. '/' by default.
        domain -- str that specifies the 'Domain' attribute. None does not set 'Domain'
                  attribute. None by default.
        secure -- bool that specifies wheter it is a secure cookie. If it is True, 'secure'
                  flag is set. If it is False, 'secure' flag is not set. False by default.
        httponly --  bool that specifies wheter it is an http only cookie. If it is True,
                     'HttpOnly' flag is set. If it is False, 'HttpOnly' flag is not set. False
                     by default.
        comment -- str that specifies the 'Comment' attribute. None does not set 'Comment'
                   attribute. None by default.
        overwrite -- bool that specifies if any existing cookie with the same key should be
                     unset before setting this cookie. False by default.
        """
        self._res.set_cookie(key, value, max_age, path, domain, secure, httponly, comment,
                             overwrite=overwrite)

    def unset_cookie(self, key):
        """
        Unset cookie with the specified key.

        key -- str that specifies the cookie name.
        """
        self._res.unset_cookie(key, False)

    def delete_cookie(self, key, path='/', domain=None):
        """
        Set cookie value to an empty str and 'Max-Age' to 0.

        key -- str that specifies the cookie name.
        path -- str that specifies the 'Path' attribute. '/' by default.
        domain -- str that specifies the 'Domain' attribute. None by default.
        """
        self._res.delete_cookie(key, path, domain)

    def __call__(self, environ, start_response):
        """
        WSGI application interface.

        environ and start_response -- objects provided by the WSGI server.
        """
        return self._res(environ, start_response)
开发者ID:ral99,项目名称:weppy,代码行数:84,代码来源:http.py

示例10: login

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import delete_cookie [as 别名]
    def login(self, request, extra = {}, **kw):
        """ Log a user into the ID server
        """
        response = {}
        error = {}
        uid = None
        email = None
        storage = self.app.storage

        if not self.is_internal(request):
            raise HTTPForbidden()
        (content_type, template) = self.get_template_from_request(request,
                                                    html_template = 'login')
        # User is not logged in or the association is not present.
        if (len(request.POST.get('id', '')) and
            len(request.POST.get('password', ''))):
            email = request.POST['id']
            password = request.POST['password']
            try:
                username = extract_username(email)
            except UnicodeError:
                # Log the invalid username for diagnostics ()
                logger.warn('Invalid username specified: %s (%s) '
                            % (email, username))
                raise HTTPBadRequest()
            # user normalization complete, check to see if we know this
            # person
            uid = self.app.auth.backend.authenticate_user(username,
                                                          password)
            if uid is None:
                error = self.error_codes.get('LOGIN_ERROR')
                logger.debug('Login failed for %s ' % email)
                body = template.render(error = error,
                                       response = response,
                                       extra = extra,
                                       request = request,
                                       config = self.app.config)
                response = Response(str(body), content_type = content_type)
                logger.debug('Nuking session cookie')
                response.delete_cookie('beaker.session.uid')
                try:
                    del request.environ['beaker.session']['uid']
                except KeyError:
                    pass
                return response
            logger.debug('setting uid to %s' % uid)
            request.environ['beaker.session']['uid'] = uid

            # if this is an email validation, skip to that.
            if 'validate' in request.params:
                return self.validate(request)
        # Attempt to get the uid.
        if not email:
            email = request.params.get('id', None)
        if uid is None:
            logger.debug('attempting to get uid')
            uid = self.get_uid(request, strict = False)
            if uid is None:
                logger.debug('no uid present')
                # Presume that this is the first time in.
                # Display the login page for HTML only
                body = template.render(error = error,
                                        response = response,
                                        config = self.app.config,
                                        extra = extra,
                                        request = request)
                response = Response(str(body), content_type = content_type)
                response.delete_cookie('beaker.session.uid')
                return response
        # Ok, got a UID, so let's get the user info
        user = storage.get_user_info(uid)
        if user is None:
            user = storage.create_user(uid, email)
        if email:
            if email not in user.get('emails', []):
                self.send_validate_email(uid, email)
            if (len(request.params.get('audience', ''))):
                return self.registered_emails(request)
            location = "%s/%s" % (self.app.config.get('oid.login_host',
                                                          'localhost'),
                 quote(email))
        else:
            del (request.environ['beaker.session']['uid'])
            location = "%s/%s/login" % (self.app.config.get('oid.login_host',
                                                            'localhost'),
                                        VERSION)
        logger.debug('Sending user to admin page %s' % location)
        raise HTTPFound(location = location)
开发者ID:rafrombrc,项目名称:FirefoxID-Server,代码行数:90,代码来源:auth.py

示例11: Context

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import delete_cookie [as 别名]

#.........这里部分代码省略.........

    def _init_template_vars(self):
        self.template_vars = build_vars(self.storage)
        # add and override variables specific to the web responses
        self.template_vars.update({
            'file': self.file,
            'path': self.path,
            'url': self.url,
            'root_url': self.root_url,
            'stylesheets': ['main.css', 'user.css'],
            'scripts': ['mootools-core-1.3.1.js', 'mootools-more-1.3.1.1.js', 'main.js'],
        })

    def render(self, template):
        return self.lookup.get_template(template).render(**self.template_vars)

    def respond(self):
        return self.res(self._environ, self._start_response)

    def iter_files(self):
        if self.object_type == "directory":
            for f in self.file.iter_children():
                if self.user.has_perms(f, f.PERM_IN):
                    yield f

    def iter_files_recursively(self):
        if self.object_type != "directory":
            return
        for root, directories, files in os.walk(self.file.get_realpath()):
            path = root[len(self.storage.root):]
            f = self.storage.get_file(path)

            if not self.user.has_perms(f, f.PERM_LIST):
                continue

            yield f
            for filename in files:
                f = self.storage.get_file(os.path.join(path, filename))
                if self.user.has_perms(f, f.PERM_IN):
                    yield f

    def login(self, user, set_cookie=True):
        """
        Log in an user.
        user: User
        set_cookie: bool, to chose if we set the cookie to remember the user.

        Do note that if you replace the "res" attribute after,
        that the cookie will not be sent.
        """
        assert user.exists
        if set_cookie:
            signer = AuthCookieSigner(secret=self.cookie_secret, timeout=120*24*60)
            cookie = signer.sign(user.name.encode('utf-8'))
            self.res.set_cookie('assnet_auth', cookie,
                max_age=timedelta(days=120), httponly=True, path=quote_url(self.root_url))
            # ensure there is a session cookie
            self.update_session()
        self.user = user

    def logout(self, delete_cookie=True):
        """
        Log out the current user.
        delete_cookie: bool, to chose if we remove the cookie to forget the user.

        Do note that if you replace the "res" attribute after,
        that the cookie will not be removed.
        """
        if delete_cookie:
            self.res.delete_cookie('assnet_auth', path=quote_url(self.root_url))
        self.user = Anonymous()

    def update_session(self):
        """
        Update the session cookie from the session attribute, encoded in plain JSON.
        It is not designed to be authoritative.
        JSON is readable client-side and allows us to restrict the types
        injected by the cookie compared to pickle.

        session should be a dict.

        Do note that if you replace the "res" attribute after,
        that the session cookie will not be sent.
        """
        self.res.set_cookie('assnet_session', json.dumps(self.session),
            path=quote_url(self.root_url))

    def _init_session(self):
        """
        Get the session cookie. It must be a dict
        and will ignore invalid data.
        """
        try:
            session = json.loads(self.req.cookies.get('assnet_session', ''))
        except ValueError:
            session = dict()
        else:
            if not isinstance(session, dict):
                session = dict()
        self.session = session
开发者ID:laurentb,项目名称:assnet,代码行数:104,代码来源:server.py


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