Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 浏览器在@login_required上正确重定向,但在使用urllib2时不正确重定向_Python_Django_Authentication_Urllib2_Login Required - Fatal编程技术网

Python 浏览器在@login_required上正确重定向,但在使用urllib2时不正确重定向

Python 浏览器在@login_required上正确重定向,但在使用urllib2时不正确重定向,python,django,authentication,urllib2,login-required,Python,Django,Authentication,Urllib2,Login Required,我正在用unnitest.TestCase测试Django应用程序 if test['auth']: full_url = '{}/{}'.format(host, test['url']) request = urllib2.Request(full_url) cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.

我正在用unnitest.TestCase测试Django应用程序

if test['auth']:
    full_url = '{}/{}'.format(host, test['url'])
    request = urllib2.Request(full_url)
    cj = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    urllib2.install_opener(opener)

    urlh = urllib2.urlopen(full_url)
    html = urlh.read()

    doc = BeautifulSoup(html)
    csrf_input = doc.find(attrs = dict(name = 'csrfmiddlewaretoken'))
    csrf_token = csrf_input['value']

    params = urllib.urlencode(dict(username = test['username'], password=test['password'], 
           csrfmiddlewaretoken = csrf_token, user=CustomUser.objects.get(id=2), next=test['url']))
    urlh = urllib2.urlopen(full_url, params)
    output = urlh.read()
    print 'Checking {} for "{}" string at {}.'.format(test['url'], test['test_string'], host)
    print output
    if test['test_string'] in output:
        return True
    else:
        return False
进入此页面的测试数据如下所示:

{
    'url' : '/manager/',
    'test_string' : 'Manage your jobs',
    'comment' : 'testing string in page',
    'hosts' : (hosts['test'],),
    'auth' : True,
    'username' : 'poster',
    'password' : 'poster',
    'active' : True,
},
*为了完整性起见:hosts['test']等于'http://:' 它为主机中的主机调用http\u字符串\u测试仪:

我试图检查的页面要求用户登录(此页面url为“/manager/”):

登录视图('/auth/login/')如下所示:

def dologin(request):

    message = 'blah'
    user = []

    if request.method == 'POST':

        username = request.POST['username']
        password = request.POST['password']

        user = authenticate(
            username = username,
            password = password,
        )

        if user is not None and hasattr(user, 'verified'):
            if user.verified and user.is_active:
                message = 'authenticated'
                login(request, user)

                # This section seems to be required so that I can redirect properly in 
                # the browser but in the test it seems to be a hindrance.
                if request.POST['next'] is not None:
                    print 'NEXT is '+str(request.POST['next'])
                    return HttpResponseRedirect(request.POST['next'])
                else:
                    return HttpResponseRedirect('/')


        # .............. #

    # The rest
    if request.method == 'GET' and 'next' in request.GET:
        next = request.GET['next']
    else:
        next = None

    print 'NEXT is '+str(next)

    return render_to_response(
        'auth/login.html',
        {
            'page_title' : 'Log in to {}'.format(SITENAME),
            'app_name' : SITENAME,
            'message' : message,
            'next' : next,
        },
        context_instance = RequestContext(request),
    )
当我运行测试时,我在日志(从.manage.py runserver)中获得以下内容:


我猜它没有正确设置cookie,尽管我不知道为什么。如果您包含了一些代码来打印所有HTTP请求和响应头,它应该有助于跟踪问题。您选择这种方式而不是Django TestCase工具,有什么原因吗?只是好奇,不要批评!看起来你在使用Django的内置身份验证系统,IIRC要求你也使用它的内置会话系统,但我没有看到会话cookie被设置。在使用您的web浏览器时,它是否设置了任何会话cookies?嗨,limelights,这是一个很好的问题,我更愿意这样做,但我还没有找到一组对我有意义或对我有帮助的好例子。我看到的当然是django文档网站。我也对这个问题持开放态度(我意识到从技术上讲这是个离题的话题,但无论如何我都会持开放态度)。。。你指的可能是这样的吗?
def dologin(request):

    message = 'blah'
    user = []

    if request.method == 'POST':

        username = request.POST['username']
        password = request.POST['password']

        user = authenticate(
            username = username,
            password = password,
        )

        if user is not None and hasattr(user, 'verified'):
            if user.verified and user.is_active:
                message = 'authenticated'
                login(request, user)

                # This section seems to be required so that I can redirect properly in 
                # the browser but in the test it seems to be a hindrance.
                if request.POST['next'] is not None:
                    print 'NEXT is '+str(request.POST['next'])
                    return HttpResponseRedirect(request.POST['next'])
                else:
                    return HttpResponseRedirect('/')


        # .............. #

    # The rest
    if request.method == 'GET' and 'next' in request.GET:
        next = request.GET['next']
    else:
        next = None

    print 'NEXT is '+str(next)

    return render_to_response(
        'auth/login.html',
        {
            'page_title' : 'Log in to {}'.format(SITENAME),
            'app_name' : SITENAME,
            'message' : message,
            'next' : next,
        },
        context_instance = RequestContext(request),
    )
Development server is running at http://<hostname:port>/
Quit the server with CONTROL-C.
[15/Apr/2013 08:21:53] "GET /manager/ HTTP/1.1" 302 0
NEXT is /manager/
[15/Apr/2013 08:21:53] "GET /auth/login/?next=/manager/ HTTP/1.1" 200 2973
[15/Apr/2013 08:21:53] "POST /manager/ HTTP/1.1" 302 0
NEXT is /manager/
[15/Apr/2013 08:21:53] "GET /auth/login/?next=/manager/ HTTP/1.1" 200 2973
HEADERS are Date: Mon, 15 Apr 2013 13:42:33 GMT
Server: WSGIServer/0.1 Python/2.7.3
Vary: Cookie
Content-Type: text/html; charset=utf-8
Set-Cookie:  csrftoken=TYEE6upwq20wNoobztYWHlIjnIQ8qc2u; expires=Mon, 14-Apr-2014 13:42:33 GMT; Max-Age=31449600; Path=/

PARAMS are username=poster&csrfmiddlewaretoken=TYEE6upwq20wNoobztYWHlIjnIQ8qc2u&password=poster&user=poster&next=%2Fmanager%2F

RESPONSE HEADERS are Date: Mon, 15 Apr 2013 13:42:33 GMT
Server: WSGIServer/0.1 Python/2.7.3
Vary: Cookie
Content-Type: text/html; charset=utf-8
Set-Cookie:  csrftoken=TYEE6upwq20wNoobztYWHlIjnIQ8qc2u; expires=Mon, 14-Apr-2014 13:42:33 GMT; Max-Age=31449600; Path=/