2012-11-07 17:53:14 +00:00
|
|
|
import sys
|
|
|
|
if sys.version_info[0] < 3:
|
|
|
|
from urllib2 import (urlopen, Request, HTTPCookieProcessor,
|
|
|
|
build_opener, install_opener)
|
|
|
|
from urllib import urlencode
|
|
|
|
else:
|
|
|
|
from urllib.request import (Request, urlopen, HTTPCookieProcessor,
|
|
|
|
build_opener, install_opener)
|
|
|
|
from urllib.parse import urlencode
|
2012-07-17 19:53:55 +00:00
|
|
|
|
|
|
|
class Connection(object):
|
|
|
|
"""
|
|
|
|
>>> conn = Connection()
|
|
|
|
>>> response = conn.login("http://blankfamily.us/login/", "username", "password")
|
|
|
|
"""
|
|
|
|
def login(self, login_url, username, password):
|
2012-11-07 17:53:14 +00:00
|
|
|
cookies = HTTPCookieProcessor()
|
|
|
|
opener = build_opener(cookies)
|
|
|
|
install_opener(opener)
|
2012-07-17 19:53:55 +00:00
|
|
|
opener.open(login_url)
|
|
|
|
try:
|
|
|
|
self.token = [x.value for x in cookies.cookiejar if x.name == 'csrftoken'][0]
|
|
|
|
except IndexError:
|
|
|
|
return Exception("no csrftoken")
|
|
|
|
params = dict(username=username,
|
|
|
|
password=password,
|
|
|
|
next="/",
|
|
|
|
csrfmiddlewaretoken=self.token,
|
|
|
|
)
|
2012-11-07 17:53:14 +00:00
|
|
|
login_data = urlencode(params)
|
|
|
|
request = Request(login_url, login_data)
|
|
|
|
response = urlopen(request)
|
2012-07-17 19:53:55 +00:00
|
|
|
if response.geturl() == login_url:
|
|
|
|
raise Exception("Invalid password")
|
|
|
|
return response
|
|
|
|
|