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()
In python interpreter:
import client
client.secret_page
--> []
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)
I hope I have made this clear.
EDIT 1:
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)]>
The response for opener.open (the POST one) is again 200 and url is the same.
I was sending the POST request to the wrong url. It was meant to be sent to:
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.