Created
December 2, 2011 13:45
-
-
Save suda/1423289 to your computer and use it in GitHub Desktop.
Simple Django view that returns list of user (identified by username and password POST parameters) basecamps from 37 Signals Launchpad
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- encoding: utf-8 -*- | |
from lxml import etree | |
from BeautifulSoup import BeautifulSoup | |
import simplejson | |
import urllib, urllib2 | |
import cookielib | |
from django.http import HttpResponse | |
from django.views.decorators.csrf import csrf_exempt | |
@csrf_exempt | |
def basecamps(request): | |
username = request.POST.get('username') | |
password = request.POST.get('password') | |
root = etree.Element("response") | |
if (username is None) or (password is None): | |
errorNode = etree.SubElement(root, 'error') | |
errorNode.text = 'Wrong parameters' | |
return HttpResponse(etree.tostring(root), mimetype='application/xml') | |
cj = cookielib.LWPCookieJar() | |
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) | |
urllib2.install_opener(opener) | |
# Get authenticity_token | |
file = urllib2.urlopen('https://launchpad.37signals.com/signin') | |
data = file.read() | |
soup = BeautifulSoup(data) | |
input = soup.find('input', {'name': 'authenticity_token'}) | |
authenticity_token = input['value'] | |
# Submit login form | |
values = { | |
'username': username, | |
'password': password, | |
'utf8': 1, | |
'authenticity_token': authenticity_token | |
} | |
valuesEncoded = urllib.urlencode(values) | |
req = urllib2.Request('https://launchpad.37signals.com/session', valuesEncoded) | |
file = urllib2.urlopen(req) | |
data = file.read() | |
if data.find('/forgot_password') != -1: | |
errorNode = etree.SubElement(root, 'error') | |
errorNode.text = 'Invalid username or password' | |
return HttpResponse(etree.tostring(root), mimetype='application/xml') | |
soup = BeautifulSoup(data) | |
accounts = soup.findAll('div', 'account') | |
accountsNode = etree.SubElement(root, 'accounts') | |
for account in accounts: | |
if account['data-product'] == 'basecamp': | |
accountNode = etree.SubElement(accountsNode, 'account') | |
accountNode.text = account['data-subdomain'] | |
return HttpResponse(etree.tostring(root), mimetype='application/xml') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment