"""
Log into Django Site
====================
By Yuji Tomita
2/22/2011
"""
import urllib
import urllib2
import contextlib
def login(login_url, username, password):
cookies = urllib2.HTTPCookieProcessor()
opener = urllib2.build_opener(cookies)
urllib2.install_opener(opener)
opener.open(login_url)
try:
token = [x.value for x in cookies.cookiejar if x.name == 'csrftoken'][0]
except IndexError:
return False, "no csrftoken"
params = dict(username=username, password=password, \
this_is_the_login_form=True,
csrfmiddlewaretoken=token,
)
encoded_params = urllib.urlencode(params)
with contextlib.closing(opener.open(login_url, encoded_params)) as f:
html = f.read()
print html
# we're in.
Published by Yuji Tomita
I'm a human person. I excel in crafting holistic technology solutions that extend beyond a narrow technical scope.
View all posts by Yuji Tomita
I had the same thing to do, unable to do it with curl, and someone on S.O. pointed me to twill…and it works really well, with much less lines of code