Python认证Cookie和django会话 [英] Python authentication cookies and django sessions

查看:117
本文介绍了Python认证Cookie和django会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个外部python客户端来访问django应用程序。客户端应该对用户进行身份验证,生成cookie,并可以像任何浏览器一样访问这些页面。

I am trying to create an external python client to access a django app. The client should authenticate a user, generate cookies and be able to access the pages just like any browser.

login_data_encoded = urllib.urlencode({'user':'sample', 'pass':'secret'})
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)
opener.open('http://localhost:8000/login', login_data_encoded)  #problem here
response = opener.open('http://localhost:8000/secret_page')
secret_page = response.read()

在python解释器中: p>

In python interpreter:

import client

client.secret_page
--> []

但是页面是空的。我可以在浏览器中查看页面(一旦以示例用户身份登录,登录工作)。 Django将我确定为匿名用户(因为由于权限,它不允许我查看示例用户的数据),也许是因为我还没有为用户启动django会话。如何通过客户端启动django会话? (不用浏览器)

But the page is empty. I can view the page in browser (once logged in as sample user, login works). Django identified me as an Anonymous User (thus due to permissions, it does not let me view the data for sample user) maybe because I have not started a django session for the user. How do I start a django session through the client? (not with a browser)

我希望我已经清楚了。

编辑1:

它以匿名用户身份登录,没有或不带斜杠。没有csrf的代码或模板。 Django的日志显示200个响应,还有200个获取secret_page。 cj包含cookie信息:

It logs me in as Anonymous user, no difference with or without slash. No csrf in code or template. Log of Django shows 200 response, and 200 on getting the secret_page as well. cj contains the cookie information:

<cookielib.CookieJar[Cookie(version=0, name='app_r12', value='dd070f7acfe37c0474c223287c5adcbe', port=None, port_specified=False, domain='localhost.local', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={}, rfc2109=False)]>

opener.open(POST一个)的响应又是200,url是一样的。

The response for opener.open (the POST one) is again 200 and url is the same.

推荐答案

我发送POST请求到错误的URL。这是要发送到:

I was sending the POST request to the wrong url. It was meant to be sent to:

opener.open('http://localhost:8000/auth', login_data_encoded)

抱歉我的错误。我以为如果我将请求发送到登录页面,它将工作,但登录页面不会进入正确的视图。将其更改为具有正确视图的URL后,其作品。

Sorry my mistake. I thought if I sent the request to the login page it would work but the login page was not going to the right view. After changing it to the url with the right view, its works.

感谢您的答案,他们真正有用。

Thank you for the answers they were really helpful.

这篇关于Python认证Cookie和django会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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