Django注销不工作 [英] Django logout not working

查看:419
本文介绍了Django注销不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎有与此问题相同的问题: Django注销问题



Mine有点威慑,它可以在谷歌chrome ....但不在firefox ...



这是我的注销功能:(在views.py中)

  def my_logout(request):
logger.debug(Logout由用户调用)
try:
#这里我做一些自定义的东西,像在数据库中记录此操作等等
#对于这个问题,这不应该是重要的...因为在尝试捕获
#所以任何错误在这里,注销应该工作反正
除了异常,e:
logger.info(记录注销操作错误:%s%e)
logout(request)
返回HttpResponseRedirect(/)

在设置中。 py我有:

  LOGIN_URL ='/ desktop / login /'
LOGOUT_URL ='/ desktop / logout /'
LOG IN_REDIRECT_URL ='/'

在应用程序的iamapps的urls.py中(包含在项目urls中) as / desktop /):

  url(r'^ login / $','iamapps.views.my_login',name = 'iamapps.login'),
url(r'^ logout / $','iamapps.views.my_logout',name ='iamapps.logout'),
/ pre>

进一步信息:




  • django 1.4.3(刚更新1.3至1.4 ....)

  • python 2.7

  • 适用于Chrome,但不适用于Firefox 17.0.1,Linux



事实上,它在谷歌Chrome中工作,但在Firefox中无法使我最难以理解。似乎它与firefox有关,请记住用户登录...



编辑:
我得到一个破碎的管道....但是我似乎得不到它的注销...但退出后的家庭视图....

 追溯(最近的最后一次呼叫):
文件/usr/lib/python2.7/wsgiref/handlers.py,第86行,运行
self.finish_response()
文件/usr/lib/python2.7/wsgiref/handlers.py,第127行,在finish_response
self.write(data)
文件/usr/lib/python2.7 /wsgiref/handlers.py,第210行,写入
self.send_headers()
文件/usr/lib/python2.7/wsgiref/handlers.py,第268行,在send_headers
self.send_preamble()
文件/usr/lib/python2.7/wsgiref/handlers.py,第192行,在send_preamble
'日期:%s\r\\\
'%format_date_time(time.time())
文件/usr/lib/python2.7/socket.py,第324行,写入
self.flush()
文件 /usr/lib/python2.7 /socket.py,行303,in flush
self._sock.sendall(view [write_offset:write_offset + buffer_size])
error:[Errno 32] Broken pipe
---- ------------------------------------
在处理请求时发生异常('127.0 .0.1',58684)
追溯(最近的最后一次调用):
文件/usr/lib/python2.7/SocketServer.py,第582行,process_request_thread
self.finish_request (request,client_address)
文件/usr/lib/python2.7/SocketServer.py,第323行,在finish_request
self.RequestHandlerClass(request,client_address,self)
文件 /media/storage/django/sites/iamfloraservice/parts/django/django/core/servers/basehttp.py,第139行,__init__
super(WSGIRequestHandler,self).__ init __(* args,** kwargs )
文件/usr/lib/python2.7/SocketServer.py,第641行,__init__
self.finish()
文件/usr/lib/python2.7/ SocketServer.py,第694行,完成
self.wfile.flush()
文件/ usr / lib / python2.7 / socket.py,行303,in flush
self._sock.sendall(view [write_offset:write_offset + buffer_size])
error:[Errno 32] Broken pipe
- ---------------------------------------
[24 / Dec / 2012 14 :33:25]GET / HTTP / 1.1200 48247

strong>
它登出后被重定向到这个视图:

  def home(request,template =' 

logger.debug(由用户%s调用的Home视图%request.user)
返回render_to_response(template,{},context_instance = RequestContext(请求))

我认为重定向与此视图的请求导致问题....
在日志中,它仍然是用户'michel'(beacuse该视图使用重定向请求,并且有用户michel)...但是...用户michel正在注销在同一时间... 。



编辑3



因为的建议是由于记录器。
无标记日志记录不帮助
这是默认的记录器:

  import logging 
logger = logging.getLogger(__ name__)

编辑4 (30-12 -2012)



我的注销是从主窗口中显示用户登录时的退出链接,如果用户注销,则显示登录链接。另外它还包含一个工具栏,这些工具根据用户和组成员的不同而被填充。



我认为问题是,它正在重新加载这个主窗口,而缓存并且其请求中的用户尚未清除。不知何故,Chrome知道如何处理这个问题,而firefox会导致管道错误。在浏览器中手动清除缓存会导致重新加载后的正确视图....



解决方案可能是重定向到没有包含用户的任何内容的页面。 ..
或找到清除缓存在正确的时刻myselve ....



这个问题描述可能是一样的...但我不能指望用户在浏览器中做任何事情只是要注销?请参阅 django 1.4缓存GET到/ login /



编辑5 (31-12-2012)



似乎这是一个缓存问题... 。但不确定如何解决这个问题。



这些是我的缓存设置:

 code>如果不是DEBUG:
CACHES = {
'default':{
'BACKEND':'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION':'127.0.0.1:11211',
}
}
else:
CACHES = {
'default':{
' BACKEND':'django.core.cache.backends.dummy.DummyCache',
}
}

但是我尝试没有dummycache也



编辑6 (4-jan-2013)
仍然没有解决方案....我改变了我注销到django的方式,我现在使用信号...看我自己的答案在下面。



但是它仍然给出了导致firefox停止注销的破坏错误。这不是缓存问题。如果我去另一个页面,甚至更糟糕的是管理页面。我还在登录注销的唯一方法是通过管理页面上的注销....如果不是管理员用户...没有办法让我在Firefox浏览器上注销。



使用管理界面注销时,信号工作正常...



我通过关闭信号进行检查....仍然退出firefox不起作用。



结论:回到主页()导致问题。



EDIT 7 (4 jan 2013)
我做了一个简单的退出视图进行测试,
这个模板:

 < HTML> 
< head>
< title>
注销
< / title>
< / head>
< body>
您已成功注销。< br>
< br>
< a href =/>返回主页< / a>
或< br>
< a href =/ desktop / login /?next = />再次登录< / a>
< / body>
< / html>

和已注销的视图:

  class LoggedOutView(TemplateView):
template_name =iamapps / logged_out.html

并将URL更改为:

  url(r'^ logout / $','django .contrib.auth.views.logout',{'next_page':'/ desktop / loggedout /'},name ='iamapps.logout'),
#url(r'^ logout / $','django ,
url(r'^ loggedout / $',LoggedOutView.as_view(),name ='iamapps.loggedout'),

仍然,简单的事情...我的信号已关闭。



,但它仍然无法在Firefox中使用....但是它在Chrome中工作。



在Firefox中,它不会转到已注销的页面

解决方案

最后我完全切换回到django默认值...
使用:



在views.py:

 从django.contrib.auth.forms导入AuthenticationForm 
from django.views.generic.edit import FormView

class LoginView(FormView):

这是django.contrib.auth.views.login的基于类的版本。



form_class = AuthenticationForm
redirect_field_name = REDIRECT_FIELD_NAME
template_name ='iamapps / login.html'


@method_decorator(csrf_protect)
@method_decorator(never_cache)
def dispatch(self,* args,** kwargs):
return super(LoginView,self).dispatch(*

$ b def form_valid(self,form):

用户提供了有效的凭据(这已在AuthenticationForm.is_valid()中检查) 。所以现在我们
可以检查测试cookie的东西并登录他。

self.check_and_delete_test_cookie()
login(self.request,form.get_user())
返回超级(LoginView,self).form_valid(form)

def get_context_data(self,** kwargs):
context = super(LoginView,self).get_context_data(* * kwargs)
apps_settings = iamapps_settings()
如果apps_settings [LOGON_BASE_APP_NAME]:
self.extend_template =%s / base.html%apps_settings [LOGON_BASE_APP_NAME]
else:
self.extend_template =iamapps / base.html
上下文['extend_template'] = self.extend_template
返回上下文

def form_invalid(self,form):

用户提供了无效的凭据(这已在AuthenticationForm.is_valid()中检查)。所以现在我们
再次设置测试cookie,并重新呈现带有错误的表单。

self.set_test_cookie()
返回超级(LoginView,self).form_invalid(form)

def get_success_url(self):
如果self.success_url:
redirect_to = self.success_url
else:
redirect_to = self.request.REQUEST.get(self.redirect_field_name,'')

netloc = urlparse.urlparse(redirect_to)[1]
如果不是redirect_to:
redirect_to = settings.LOGIN_REDIRECT_URL
#安全检查 - 不允许重定向到不同的主机
elif netloc和netloc!= self.request.get_host():
redirect_to = settings.LOGIN_REDIRECT_URL
return redirect_to

def set_test_cookie(self):
self.request .session.set_test_cookie()

def check_and_delete_test_cookie(self):
如果self.request.session.test_cookie_worked():
self.request.session.delete_test_cooki e()
return True
return False

def get(self,request,* args,** kwargs):

Same作为django.views.generic.edit.ProcessFormView.get(),但添加测试cookie的东西

self.set_test_cookie()
返回超级(LoginView,self).get请求,* args,** kwargs)

和urls:

  url(r'^ login / $',LoginView.as_view(),name ='login'),
/ pre>

这解决了我所有的麻烦...关于登录和登录...



登录和注销信号正常工作:

  from django.contrib.auth.signals import user_logged_out,user_logged_in 

#注意,这些登录和注销信号在imamstats视图中注册
def iam_logged_out_actions(发件人,用户,请求,** kwargs):
try:
#...做我的日志out actiosn(stats等)
除了异常, e:
logger.error(Logging logout action error:%s%e)

#注意,这些登录和注销信号在imamstats视图中注册
def iam_logged_in_actions发件人,用户,请求,** kwargs):
尝试:
#...做我的日志统计等东西
除了异常,e:
logger.error( 登录登录操作错误:%s%e)


I seem to have the same problem as in this question: Django logout problem

Mine is a bit weirder, it works in google chrome.... but not in firefox...

this is my logout function: (in views.py)

def my_logout(request):
    logger.debug("Logout called by user")
    try:
        # Here I do some custom stuff, like logging this action in a database and so on
        # For this question it shouldn't matter... because in a try catch
        # so whatever goes wrong here, logging out should work anyway
    except Exception, e:
        logger.info("Logging logout action error: %s" % e)
    logout(request)
    return HttpResponseRedirect("/")

in settings.py I have:

LOGIN_URL = '/desktop/login/'
LOGOUT_URL = '/desktop/logout/'
LOGIN_REDIRECT_URL = '/'

And in the urls.py of the app iamapps (include in the project urls as /desktop/):

url(r'^login/$', 'iamapps.views.my_login', name='iamapps.login'),
url(r'^logout/$', 'iamapps.views.my_logout', name='iamapps.logout'),

further info:

  • django 1.4.3 (just updated from 1.3 to 1.4 ....)
  • python 2.7
  • works in Chrome but not in Firefox 17.0.1, Linux

The fact that it does work in google chrome but does not work in firefox puzzles me the most. Seems it has something to do with firefox keeps remembering the user as being logged on...

EDIT: I get a broken pipe.... but I seem to get it not on logging out... but going to the home view after logout....

Traceback (most recent call last):
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 86, in run
    self.finish_response()
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 127, in finish_response
    self.write(data)
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 210, in write
    self.send_headers()
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 268, in send_headers
    self.send_preamble()
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 192, in send_preamble
    'Date: %s\r\n' % format_date_time(time.time())
  File "/usr/lib/python2.7/socket.py", line 324, in write
    self.flush()
  File "/usr/lib/python2.7/socket.py", line 303, in flush
    self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 58684)
Traceback (most recent call last):
  File "/usr/lib/python2.7/SocketServer.py", line 582, in process_request_thread
    self.finish_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 323, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/media/storage/django/sites/iamfloraservice/parts/django/django/core/servers/basehttp.py", line 139, in __init__
    super(WSGIRequestHandler, self).__init__(*args, **kwargs)
  File "/usr/lib/python2.7/SocketServer.py", line 641, in __init__
    self.finish()
  File "/usr/lib/python2.7/SocketServer.py", line 694, in finish
    self.wfile.flush()
  File "/usr/lib/python2.7/socket.py", line 303, in flush
    self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe
----------------------------------------
[24/Dec/2012 14:33:25] "GET / HTTP/1.1" 200 48247

Edit 2 it goes to this view after loging out and being redirected:

def home(request, template='iamfloraservice/home.html'):

    logger.debug("Home view called by user %s" % request.user)
    return render_to_response(template,{},context_instance=RequestContext(request))

I think the redirect with the request to this view causes the problem.... In the log sais it's still user 'michel' (beacuse the view uses the request from the redirect, and that had user michel)... however... user michel is being logged out in the mean time....

EDIT 3

because of the suggestion it's due to the logger. unremarking the logging does not help And it's the default logger:

import logging
logger = logging.getLogger(__name__)

EDIT 4 (30-12-2012)

My logout is from a main window where I show a logout link when a user is logged on and a login link if a user is logged out. Also it contains a toolbar, which tools are filled depending on the the user and it's membership of groups.

I think the problem is, it's reloading this main window while the cache and the user in it's request isn't cleared yet. Somehow Chrome knows how to handle this, and firefox results in a broken pipe error. Clearing the cache manually in the browser results in the correct view after reload....

a solution might be to redirect to a page without anything in it that contains users... or find out to clear the cache on the right moment myselve....

this problem describes maybe the same... but I cannot expect users to do anything in the browser just to logout? see django 1.4 caching GET to /login/

Edit 5 (31-12-2012)

It seems it's a caching problem.... but not sure how to fix this yet.

these are my caching settings:

if not DEBUG:
    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
            'LOCATION': '127.0.0.1:11211',
        }
    }
else:
    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
        }
    }

But I tried without the dummycache as well

EDIT 6 (4-jan-2013) Still no solution.... I changed the way I log out to the django way, and I Am using the signals now... see my own answer below.

but still it gives the brokenpipe error which causes firefox stopping logging out. It's not a caching problem. If I go to another page, or even worse... the admin pages. I Am still logged on. The only way to logout is through the logout on the admin page.... If it's not an admin user... there is no way to get me logged out on the firefox browser.

When logging off using the admin interface, so the signal works fine...

I checked by turning off the signal.... and still the logging out in firefox does not work.

Conclusion: going back to the main page () is causing the problem.

EDIT 7 (4 jan 2013) I made a simple loggedout view for testing, this template:

<html>
<head>
<title>
Logged out
</title>
</head>
<body>
You are succesfully logged out.<br>
<br>
<a href="/">Go back to the main page</a>
or<br>
<a href="/desktop/login/?next=/">log in again</a>
</body>
</html>

and the logged out view:

class LoggedOutView(TemplateView):
    template_name = "iamapps/logged_out.html"

and changed the urls in to:

url(r'^logout/$', 'django.contrib.auth.views.logout',  {'next_page': '/desktop/loggedout/'}, name='iamapps.logout'),
#url(r'^logout/$', 'django.contrib.auth.views.logout_then_login',  name='iamapps.logout'),
url(r'^loggedout/$', LoggedOutView.as_view(),name='iamapps.loggedout'),

and still, to simplyfy things... I have the signals turned off.

and it's still not working in firefox.... but it works in chrome

In firefox it does not go to the logged out page

解决方案

Finally I totally switched to almost back to django defaults... Using:

in views.py:

from django.contrib.auth.forms import AuthenticationForm
from django.views.generic.edit import FormView

class LoginView(FormView):
    """
    This is a class based version of django.contrib.auth.views.login.


    """
    form_class = AuthenticationForm
    redirect_field_name = REDIRECT_FIELD_NAME
    template_name = 'iamapps/login.html'


    @method_decorator(csrf_protect)
    @method_decorator(never_cache)
    def dispatch(self, *args, **kwargs):
        return super(LoginView, self).dispatch(*args, **kwargs)

    def form_valid(self, form):
        """
        The user has provided valid credentials (this was checked in AuthenticationForm.is_valid()). So now we
        can check the test cookie stuff and log him in.
        """
        self.check_and_delete_test_cookie()
        login(self.request, form.get_user())
        return super(LoginView, self).form_valid(form)

    def get_context_data(self, **kwargs):
        context = super(LoginView, self).get_context_data(**kwargs)
        apps_settings=iamapps_settings()
        if apps_settings[LOGON_BASE_APP_NAME]:
            self.extend_template="%s/base.html" % apps_settings[LOGON_BASE_APP_NAME]
        else:
            self.extend_template="iamapps/base.html"
        context['extend_template']=self.extend_template
        return context    

    def form_invalid(self, form):
        """
        The user has provided invalid credentials (this was checked in AuthenticationForm.is_valid()). So now we
        set the test cookie again and re-render the form with errors.
        """
        self.set_test_cookie()
        return super(LoginView, self).form_invalid(form)

    def get_success_url(self):
        if self.success_url:
            redirect_to = self.success_url
        else:
            redirect_to = self.request.REQUEST.get(self.redirect_field_name, '')

        netloc = urlparse.urlparse(redirect_to)[1]
        if not redirect_to:
            redirect_to = settings.LOGIN_REDIRECT_URL
        # Security check -- don't allow redirection to a different host.
        elif netloc and netloc != self.request.get_host():
            redirect_to = settings.LOGIN_REDIRECT_URL
        return redirect_to

    def set_test_cookie(self):
        self.request.session.set_test_cookie()

    def check_and_delete_test_cookie(self):
        if self.request.session.test_cookie_worked():
            self.request.session.delete_test_cookie()
            return True
        return False

    def get(self, request, *args, **kwargs):
        """
        Same as django.views.generic.edit.ProcessFormView.get(), but adds test cookie stuff
        """
        self.set_test_cookie()
        return super(LoginView, self).get(request, *args, **kwargs)

and urls:

url(r'^login/$', LoginView.as_view(), name='login'),

This solved all my troubles... about loggin and logiing off on...

the login and logout signals just working fine:

from django.contrib.auth.signals import user_logged_out, user_logged_in

# Note, these login and logout signals are registered in imamstats views
def iam_logged_out_actions(sender, user, request, **kwargs):
    try:
        # ... do my logging out actiosn (stats etc.)
    except Exception, e:
        logger.error("Logging logout action error: %s" % e)

# Note, these login and logout signals are registered in imamstats views
def iam_logged_in_actions(sender, user, request, **kwargs):
    try:
        # ... do my log in stats etc. things
    except Exception, e:
        logger.error("Logging login action error: %s" % e)

这篇关于Django注销不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆