On 23/02/2011 11:51, Mike Ramirez wrote:
...........


Have your tried urllib2.Request[1] to POST your login data, how a browser
would do it?


yes
.......

eventually I got this to work with 1.2.5 (and the tutorial site); the main problems were that hitting admin to get the csrfmiddlewaretoken pops up a login page which posts back to /admin/ (not /admin/login/); also it seems we need to add in the extra hidden variable this_is_the_login_form to make things work better.

import urllib2, urllib, cookielib

site='http://127.0.0.1:8000'
cj = cookielib.CookieJar()

# build opener with HTTPCookieProcessor
o = urllib2.build_opener( urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener( o )


print 1, 30*'='
for cookie in cj:
        print cookie.domain, cookie.path, cookie.name, cookie.value
# perform login with params
f = o.open( site + '/admin/')
data = f.read()
f.close()
print 1,30*'!'
print data
D={ 'username': 'myuser', 'password': 'mypassword', 'this_is_the_login_form': 
'1'}
tl = [l for l in data.split('\n') if 'csrfmiddlewaretoken' in l]
if not tl:
        raise ValueError('no csrf token found')
tl = tl[0].split('value=')
tl = tl[1].split(' ')[0].strip('"\'')
D['csrfmiddlewaretoken'] = tl
p = urllib.urlencode(D)

print 2, 30*'='
for cookie in cj:
        print cookie.domain, cookie.path, cookie.name, cookie.value

f = o.open( site + '/admin/',p)
data = f.read()
f.close()
print 2,30*'!'
print data

# second request should automatically pass back any
# cookies received during login... thanks to the HTTPCookieProcessor
print 3, 30*'='
for cookie in cj:
        print cookie.domain, cookie.path, cookie.name, cookie.value

f = o.open( site+'/admin/')
data = f.read()
f.close()
print 3,30*'!'
print data



--
Robin Becker

--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to